ajax 发送 put 请求

ajax是不能直接发送put请求的。

原因是:

    在tomcat中,是将请求的数据,封装成一个map的,

    在获取数据时,调用 request.getParameter("name"); 时,就是从这个map中获取查找数据的,

    在springmvc封装POJO对象时,会把POJO中每个属性的值,使用 request.getParameter("name");拿到。

而在ajax发送put请求时,tomcat一看是put请求,所以不会封装请求体中的数据为map,只有post请求才会封装请求体数据为map

当然了,肯定是有解决方法的

第1种解决方法:

在web.xml中配置过滤器

	<!-- 使用rest风格的url 将页面普通的post请求转化为delete或者put请求 -->
	<filter>
		<filter-name>HiddenHttpMethodFilter</filter-name>
		<filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
	</filter>
	<filter-mapping>
		<filter-name>HiddenHttpMethodFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>

其实在写ajax请求时跟平常的也大差不差,只是在data后面在一个  + "&_method=put", 即可

$.ajax({
    url : "user/" + $(this).attr("id"),
    type : "post",
    data : $("#userUpdateModal form").serialize()+ "&_method=put",
    success : function(result) {
    console.log(result.msg);
    }
});

第二种解决方法:

在web.xml中配置

<filter>
	<filter-name>HttpPutFormContentFilter</filter-name>
	<filter-class>org.springframework.web.filter.HttpPutFormContentFilter</filter-class>
</filter>
<filter-mapping>
	<filter-name>HttpPutFormContentFilter</filter-name>
	<url-pattern>/*</url-pattern>
</filter-mapping>

然后在ajax中就可以直接使用put请求了

$.ajax({
    url : "user/" + $(this).attr("id"),
    type : "put",
    data : $("#userUpdateModal form").serialize(),
    success : function(result) {
    console.log(result.msg);
    }
});

猜你喜欢

转载自blog.csdn.net/qq_37638061/article/details/82260264