开发环境:Tomcat9.0 在使用Ajax实现Restful的时候,有时候会出现无法Put、Delete请求参数无法传递到程序中的尴尬情况,此时我们可以有两种解决方案:1、使用地址重写的方法传递参数。2、配置web.xml项目环境。
测试的程序为:
@RequestMapping(value = "/member",method = RequestMethod.PUT,produces = "application/json;charset=UTF-8")
public @ResponseBody Object edit(Member vo1) {
log.info("【*** 修改用户信息 ***】" + vo1);
JSONObject obj = new JSONObject();
obj.put("flag",true);
return obj;
}
一、使用地址重写的方法来实现put、delete请求的参数传递。 在js页面中(
1
2
3
4
5
6
7
8
9
10
11
12
13
14
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
$(editMember).on("click",function(){
$.ajax({
url : "member?empno=1009&ename=阿伦&sal=19777.77&hiredate=1969-10-10",
type : "put",0); box-sizing: border-box;">// 此处发送的是PUT请求(可变更为其他需要的请求)
dataType : "json",0); box-sizing: border-box;">// 返回的数据类型为json类型
success : (data) {
$(showDiv).append("<p>修改处理结果:" + data.flag + "</p>") ;
},error : "<p>对不起,出错啦!</p>") ;
}
}) ;
}) ;
二、使用配置文件修改来实现Put和Delete请求的参数传递 1、解决Put请求的参数传递,但是无法解决 Delete请求的传递 ①、在项目中的web.xml文件中配置:
1
2
3
4
5
6
7
8
<filter>
<filter-name>HttpMethodFilter</filter-name>
<filter-class>org.springframework.web.filter.HttpPutFormContentFilter</class>
</filter>
<filter-mapping>
<filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
②在js文件中:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
$(editBut).on((){
$.ajax({
url: "member",type : // 此处发送的是PUT请求
data : {
empno : 1170,ename : "SMITH",sal : 11.1,hiredate : "1991-11-11"
},success : (data){
$(showDiv).append("<p> 数据更新成功:"+data.flag+"</p>");
console.log(1);
},dataType : "<p>对不起,出错啦!</p>");
}
})
});
2、解决Put和Delete请求的参数传递。 ①、在项目中的web.xml文件中配置:
1
2
3
4
5
6
7
8
9
<filter>
filter-name>HiddenHttpMethodFilter</filter-name>
filter-class>org.springframework.web.filter.HiddenHttpMethodFilterfilter-class>
filter>
filter-mapping>
filter-name>
servlet-name>springmvcservlet-name>
filter-mapping>
②在js文件中:
$(editBut).on("post",0); box-sizing: border-box;">// 此处发送的是POST请求
data : {
_method : // 将请求转变为PUT请求
empno : "22222-11-11"
},0); box-sizing: border-box;">"<p>对不起,出错啦!</p>");
}
})
}); (编辑:李大同)
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!
|