springboot+layui用js發送put請求,並接收對象


有以下幾點要注意的

springboot中要設置這個過濾器,如果是在springmvc中,就在web.xml中設置,道理是一樣的

@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {
	// 就是這個
	@Bean
	public HttpPutFormContentFilter httpPutFormContentFilter() {
		return new HttpPutFormContentFilter();
	}

} 

在Controller中要在接收的對象前面設置@RequestBody

	@RequestMapping(value = "/test", method = { RequestMethod.PUT })
	public JSONObject gmm(@RequestBody UserVo userVo) throws Exception {
		JSONObject obj = new JSONObject();
		System.out.println("---------------");
		return obj;
	}

  

layui中的請求方法

    var url = "/test";
    var data = JSON.stringify($('.layui-form').serializeObject());//這個方法很關鍵JSON.stringify(),沒有這個方法后台轉換不了
    ajaxsubmit(url,data);
    function ajaxsubmit(url,data){
    	$.ajax({
     	    headers: {
     	        'Accept': 'application/json',
     	        'Content-Type': 'application/json'
     	    },
    	    url:url,
    	    data:data,
    	    type:"PUT",
    	    dataType:"json",
    	    success:function(data){
    	        if(typeof(data) != 'undefined'){
    	            layer.msg(data.message);	
    				setTimeout(function(){reload()},1*1000);
    	        }else{
    	        	layer.msg("返回錯誤,請聯系管理員!");	
    	        }
    	    },
    	    error:function(data){
    	    	layer.msg("請求錯誤,請聯系管理員!");	
    	    }
    	});
    	}

  附一個form轉json對象的辦法,這個方法上面有用到,是自定義的

    $.prototype.serializeObject = function () {
        var a,o,h,i,e;
        a = this.serializeArray();
        o={};
        h=o.hasOwnProperty;
        for(i=0;i<a.length;i++){
            e=a[i];
            if(!h.call(o,e.name)){
                o[e.name]=e.value;
            }
        }
        return o;
    }

  參考鏈接

https://blog.csdn.net/kshon/article/details/82682768

https://blog.csdn.net/pingweicheng/article/details/81019850

https://blog.csdn.net/qq_37144354/article/details/79922048

https://blog.csdn.net/weixin_33973609/article/details/93323390

    

摘錄第4篇參考文章關於傳參的一些總結:

1:JSON提交方式: Content-Type:application/json 后端:對象接收:除了:get請求,不需要增加@ReqeustBody注解,其它的都需要。 參數接收:使用:@RequestParam 或者不用。 使用這種請求: 其它后端同事開發的時候:客戶端(SOAP)模擬請求時,有了@ReqeustBody參數接收不到,於是去掉,前端開發時,更新代碼又加上。因為公司網不能下載插件,后換成了:form表單提交。 2:form表單提交方式:Content-Type:application/x-www-form-urlencoded form表單數據格式:為:param1=111
&param2=222 這種開式。 后端:對象接收:除了:所有請求:都不加@ReqeustBody注解 參數接收:可以使用:@RequestParam 或者不用。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM