ajax发送put/delete请求时出现错误的原因和解决方案

https://www.cnblogs.com/roobtyan/p/9576685.html

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>HiddenHttpMethodFilterfilter-name>
        <filter-class>org.springframework.web.filter.HiddenHttpMethodFilterfilter-class>
    filter>
    <filter-mapping>
        <filter-name>HiddenHttpMethodFilterfilter-name>
        
        <servlet-name>springmvcservlet-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){
    	
    		},
    			
       });
    }

客户端需要使用@RequestBody标注

    @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 , 可参考如下解决方案

https://stackoverflow.com/questions/12409600/error-request-header-field-content-type-is-not-allowed-by-access-control-allow

可以写一个过滤器

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

原文链接:https://blog.csdn.net/liuyuanjiang109/article/details/78972644

你可能感兴趣的:(网络,java,http,ajax,put,delete,restful)