今天 遇到了一個很神奇的問題,我使用ajax向後端傳輸數據的時候,發現使用json格式無法傳輸,後端要麼報400參數錯誤,要麼就是接收不到參數;
問題代碼
前端代碼:
<body>
<input type="button" id="but" value="測試" style="width: 200px;height: 200px"/>
</body>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
<script>
$(function () {
$("#but").click(function () {
$.ajax({
url:"/test", //調用java後臺代碼發送驗證碼
contentType: "application/json", //必須這樣寫
dataType:"json",
type:"post",
data:{"mobile": "18539204094","code":"123456"},
timeout:10000,
success:function(data){
if(data=="success"){
alert("success");
}else{
alert(data);
}
},
error:function(data){
alert("error");
}
});
})
})
</script>
後端代碼:
@PostMapping("/test")
@ResponseBody
public String test01(Mobile mobile){
System.out.println("成功!"+mobile.getMobile()+"驗證碼:"+mobile.getCode());
return "success";
}
然而執行結果,卻是無法接受到參數,參數爲null
經過一系列研究之後,發現了問題的所在;
contentType: "application/json",
就是這個配置的問題,加上了這個配置,後端就接受不到參數;
而如果不加這個參數,後端則可以接收到參數;
這是什麼原因呢?
不加這個參數,ajax會默認的使用
contentType: "application/x-www-form-urlencoded"
而這個配置,程序會將你的參數與後端接收的參數,來一個適配,所以不會出現參數錯誤的問題;
問題既然知道出在什麼地方,那麼怎麼解決?
解決方案
其實很簡單,只需要在方法的參數前面加上這個註解就ok了
@PostMapping("/test")
@ResponseBody
public String test01(@RequestBody Mobile mobile){
System.out.println("成功!"+mobile.getMobile()+"驗證碼:"+mobile.getCode());
return "success";
}
@RequestBody
這個參數的意思就是接收json形式的參數,所以如果加上這個參數,前端ajax必須使用
contentType: "application/json",
這個配置;
其實在互聯網中,傳輸格式一般都是使用json的格式,所以大家在自己項目中,最好也使用這種規範;
當然,你精準了參數格式,在前後端傳輸的時候,效率會提升一點點,因爲不用再去適配了嘛,
json格式傳過去,對就返回成功,不對就返回錯誤,肯定比再去適配參數格式,來的更快一點!