ajax使用restful服務發送put 和 delete 請求時直接傳參會出現問題html
ajax發送put 和 delete 請求時,須要傳遞參數,若是參數在url地址欄上,則能夠正常使用,前端
若是在 data:中須要傳遞參數,(瀏覽器會使用表單提交的方式進行提交) 則須要注意此時應做以下修改:web
data:{_method:"DELETE", id:issueId,userId:userId},
@RequestMapping(value="/answer/{answerId}",method=RequestMethod.DELETE) public ResponseResult deleteAnswer(@PathVariable("answerId")int answerId,Issue issue){ //可自動封裝成對象時,可直接採用對象參數 }
<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){ } }, });
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){ }
3.最後若是前端報錯 提示 Request header field Content-Type is not allowed by Access-Control-Allow-Headers in preflight response , 可參考以下解決方案ajax
能夠寫一個過濾器json
@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); } }