AJAX發送 PUT和DELETE請求(轉載)
ajax使用restful服務發送put 和 delete 請求時直接傳參會出現問題
一,采用POST + _method:delete/put + filter 的方法
ajax發送put 和 delete 請求時,需要傳遞參數,如果參數在url地址欄上,則可以正常使用,
如果在 data:中需要傳遞參數,(瀏覽器會使用表單提交的方式進行提交) 則需要注意此時應作如下修改:
1. 請求方式設置為 type:"post",
2. 在data中加入 __method:"DELETE",或者 _method:"PUT" 參數 ,
data:{_method:"DELETE", id:issueId,userId:userId},
3.后台的controller 仍為對應的DELETE 請求
@RequestMapping(value="/answer/{answerId}",method=RequestMethod.DELETE)
public ResponseResult deleteAnswer(@PathVariable("answerId")int answerId,Issue issue){
//可自動封裝成對象時,可直接采用對象參數
}
4.需要配置相應的filter(如果使用Spring Boot 則會自動配置)
<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>
ajax代碼如下 :
var r=confirm("確認刪除該?"); if(r){ $.ajax({ url:"http://localhost:8888/answer/"+answerId, type:"POST", data:{_method:"DELETE", id:issueId,userId:userId}, dataType:"json", success:function(result){ } }, });
二,仍然使用PUT DELETE 請求
1.仍然使用put和delete請求,並且需要傳遞參數的時候data需要設置為json字符串
var jsonstr = {"id":issueId,"userId":userId}; var r=confirm("確認刪除該回答?"); if(r){ $.ajax({ url:"http://localhost:8885/answer/"+answerId, type:"DELETE", contentType:"application/json",//設置請求參數類型為json字符串 data:JSON.stringify(jsonstr),//將json對象轉換成json字符串發送 dataType:"json", success:function(result){ }, }); }
2.客戶端需要使用@RequestBody標注
@RequestMapping(value="/answer/{answerId}",method=RequestMethod.DELETE)
public ResponseResult deleteAnswer(@PathVariable("answerId")int answerId,@RequestBody Issue issue){
}
3.最后如果前端報錯 提示 Request header field Content-Type is not allowed by Access-Control-Allow-Headers in preflight response , 可參考如下解決方案
可以寫一個過濾器
@WebFilter(servletNames={"dispatcherServlet"})//可配置對應的請求servlet 此處使用 springMVC
public class AjaxFilter implements Filter{
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
HttpServletResponse httpServletResponse=(HttpServletResponse) response;
httpServletResponse.setHeader("Access-Control-Allow-Origin", "*");
httpServletResponse.setHeader("Access-Control-Allow-Methods","GET,POST,DELETE,PUT");
httpServletResponse.setHeader("Access-Control-Allow-Headers","Origin,X-Requested-With,Content-Type,Accept");
chain.doFilter(request, response);
}
}
