Ajax中Put和Delete請求傳遞引數無效的解決方法(Restful風格
阿新 • • 發佈:2019-01-30
在使用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;
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 1
- 2
- 3
- 4
- 5
- 6
- 7
一、使用地址重寫的方法來實現put、delete請求的引數傳遞。
在js頁面中(
$(editMember).on("click",function(){
$.ajax({
url : "member?empno=1009&ename=阿倫&sal=19777.77&hiredate=1969-10-10" , // 處理的請求路徑
type : "put" , // 此處傳送的是PUT請求(可變更為其他需要的請求)
dataType : "json" , // 返回的資料型別為json型別
success : function(data) {
$(showDiv).append("<p>修改處理結果:" + data.flag + "</p>") ;
} ,
error : function(data) {
$(showDiv).append("<p>對不起,出錯啦!</p>" ) ;
}
}) ;
}) ;
- 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
二、使用配置檔案修改來實現Put和Delete請求的引數傳遞
1、解決Put請求的引數傳遞,但是 無法解決 Delete 請求的傳遞
①、在專案中的web.xml檔案中配置:
<filter>
<filter-name>HttpMethodFilter</filter-name>
<filter-class>org.springframework.web.filter.HttpPutFormContentFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>HttpMethodFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
②在js檔案中:
$(editBut).on("click",function(){
$.ajax({
url: "member",
type : "put", // 此處傳送的是PUT請求
data : {
empno : 1170,
ename : "SMITH",
sal : 11.1,
hiredate : "1991-11-11"
},
success : function(data){
$(showDiv).append("<p> 資料更新成功:"+data.flag+"</p>");
console.log(1);
},
dataType : "json",
error : function(data){
$(showDiv).append("<p>對不起,出錯啦!</p>");
}
})
});
- 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
2、解決 Put和Delete 請求的引數傳遞。
①、在專案中的web.xml檔案中配置:
<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>springmvc</servlet-name>
</filter-mapping>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
②在js檔案中:
$(editBut).on("click",function(){
$.ajax({
url: "member",
type : "post", // 此處傳送的是POST請求
data : {
_method : "put", // 將請求轉變為PUT請求
empno : 1170,
ename : "SMITH",
sal : 11.1,
hiredate : "11111-11-11"
},
success : function(data){
$(showDiv).append("<p> 資料更新成功:"+data.flag+"</p>");
console.log(1);
},
dataType : "json",
error : function(data){
$(showDiv).append("<p>對不起,出錯啦!</p>");
}
})
});