ajax post傳一個json一個string字符串的方式:


第一種:傳兩個string:
1.把json轉成字符串JSON.stringify(resjson)
2.不要指定header為application/json 不寫默認是application/x-www-form-urlencoded
3.后台用兩個String加@RequestParam注解接收 然后再把json轉換為map
代碼:


/////////////AJAX
$.ajax(app.GlobalIP + '/show/addData', {
data: {
parameter: JSON.stringify(resjson),    //json to string
tablename: detailglobaltn    //字符串
},
dataType: 'json', //服務器返回json格式數據
type: 'post', //HTTP請求類型
timeout: 10000, //超時時間設置為10秒;
// headers: { 'Content-Type': 'application/json' }, //寫上后后台需要添加RequestBody 接收到的為一整個對象
success: function (data) {
console.log(JSON.stringify(data));
},
error: function (xhr, type, errorThrown) {
//異常處理;
console.log('ERROR********************' + type);
}
});
/////////////后台Controller public CommonResult addData(@RequestParam(
"parameter") String parameter, @RequestParam("tablename") String tablename){ //Map map = JSON.parseObject(parameter); Map<String,String> map = JSONObject.parseObject(parameter,new TypeReference<Map<String, String>>(){}); String s = map.get("ETIEM"); System.out.println(map); System.out.println(tablename); //...... return new CommonResult(200,"成功"); }

 

第二種:直接傳對象套對象
1.resjson直接為js的json對象
2.加上headers
3.后台用一個Map加@RequestBody注解接收 類型為Map<Map<String,Object>>
代碼:

////////////AJAX
$.ajax(app.GlobalIP + '/show/addData', { data: { parameter: resjson, //json tablename: detailglobaltn //字符串 }, dataType: 'json', //服務器返回json格式數據 type: 'post', //HTTP請求類型 timeout: 10000, //超時時間設置為10秒; headers: { 'Content-Type': 'application/json' }, //寫上后后台需要添加RequestBody 接收到的為一整個對象 success: function (data) { console.log(JSON.stringify(data)); }, error: function (xhr, type, errorThrown) { //異常處理; console.log('ERROR********************' + type); } });
////////////后台Controller public CommonResult addData(@RequestBody Map map){ Object o
= map.get("parameter"); Map parameter = JSON.parseObject(JSON.toJSONString(o)); //Map<String,String> map = JSON.parseObject(parameter,new TypeReference<Map<String, String>>(){}); String tablename = map.get("tablename").toString(); //...... return new CommonResult(200,"成功"); }

 


免責聲明!

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



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