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>
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); } }