AJAX傳送 PUT和DELETE請求注意事項
阿新 • • 發佈:2019-02-01
ajax使用restful服務傳送put 和 delete 請求時直接傳參會出現問題
一,採用POST + _method:delete/put + filter 的方法
ajax傳送put 和 delete 請求時,需要傳遞引數,如果引數在url位址列上,則可以正常使用,
如果在 data:中需要傳遞引數,(瀏覽器會使用表單提交的方式進行提交) 則需要注意此時應作如下修改:
1. 請求方式設定為 type:"post",
2. 在data中加入 __method:"DELETE",或者 _method:"PUT" 引數 ,
3.後臺的controller 仍為對應的DELETE 請求data:{_method:"DELETE", id:issueId,userId:userId},
@RequestMapping(value="/answer/{answerId}",method=RequestMethod.DELETE)
public ResponseResult deleteAnswer(@PathVariable("answerId")int answerId,Issue issue){
//可自動封裝成物件時,可直接採用物件引數
}
4.需要配置相應的filter(如果使用Spring Boot 則會自動配置)
ajax程式碼如下 :<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>
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字串客戶端需要使用@RequestBody標註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){ }, }); }
@RequestMapping(value="/answer/{answerId}",method=RequestMethod.DELETE)
public ResponseResult deleteAnswer(@PathVariable("answerId")int answerId,@RequestBody Issue issue){
}
最後如果前端報錯 提示 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);
}
}