ajax中发送delete请求,后台无法收到的解决方法

场景

最近了解了restful风格的url的设计,所以在练手项目中想尝试一下,但是在尝试中遇到了标题所示的问题,后台接收的参数适中为null,真是气爆哦。困扰了我非常之久,后来总算找到了解决方法

步骤

1.首先,也是最重要的,就是在web.xml中增加一个过滤器

<!--解决ajax无法进行PUT、DELETE请求无法传递参数-->
    <filter>
      <filter-name>HiddenHttpMethodFilter</filter-name>
      <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
    </filter>
    <filter-mapping>
      <filter-name>HiddenHttpMethodFilter</filter-name>
      <!-- 备注,这边的名称必须和配置'springmvc'的servlet名称一样 -->
      <servlet-name>spring-mvc</servlet-name>
    </filter-mapping>

至于为什么要增加这个过滤器呢,是因为 浏览器form表单只支持GET与POST请求,而DELETE、PUT等method并不支持,spring3.0添加了一个过滤器,可以将这些请求转换为标准的http方法,使得支持GET、POST、PUT与DELETE请求,该过滤器为HiddenHttpMethodFilter。

2.接下来,要更改js中部分代码

$.ajax({
            type:"POST",//此处仍然使用post
            url:"xxxx",
            async:false,
            traditional:true,
            dataType:"json",
            data:{
                _method:"DELETE", //这里是要修改的部分
                "id":xxx
            },
            success:function (result) {
                console.log(result);
                alert("haha");
            }
        })
这样就可以解决啦!


猜你喜欢

转载自blog.csdn.net/qq_37410328/article/details/80550839