對於ajax 和springmvc 傳遞值的一些總結 contentType和datatype
例子1: 比較簡單的型別,直接傳遞值到controller裡面的物件裡面的屬性,
注意這裡沒有寫 contentType : 'application/json;charset=utf-8', //設定請求頭資訊
$.ajax({
type: "POST",
url: "/restaurant/addDishes",
data: {// 和controller Tb_dishes__inf 物件裡面的屬性對應
dishes_name:'京醬肉絲',
img_path:'jjrs.jpg',
dish_description:'好吃不貴',
price:0.1,
category_id:12,
shop_id:1
},
dataType:"json", //伺服器返回值型別是json
success: function(data){
console.log(data);
},
error: function(res){
}
});
@RequestMapping("addDishes")
public ServerResponse addDishes(Tb_dishes__inf dishes) {
}
2比較複雜型別瀏覽器向後端傳遞json陣列
注意這裡 寫 contentType : 'application/json;charset=utf-8', //設定請求頭資訊
var userList = new Array();
userList.push({dishes_id: 1,totalcount:3}); //和後端list 數組裡面的 Tb_order_dishes_inf物件屬性保持一致
userList.push({dishes_id:2,totalcount: 5});
$.ajax({
type: "POST",
url: "/restaurant/createOrder?userId=2",
data: JSON.stringify(userList),//將物件序列化成JSON字串
dataType:"json", //伺服器返回值型別是json
contentType : 'application/json;charset=utf-8', //設定請求頭資訊 ,因為這裡傳遞的是json陣列
success: function(data){
console.log(data);
},
error: function(res){
}
});
後端接受
@RequestMapping("createOrder")
public ServerResponse createOrder(@RequestParam(value = "userId", required = false) Integer userId,
@RequestBody(required = false) List<Tb_order_dishes_inf> dishesList) {
if (userId == null) {
return ServerResponse.createByILLEGAL_ARGUMENT("userId 不能為空!");
}
if (dishesList == null || dishesList.size() == 0) {
return ServerResponse.createByILLEGAL_ARGUMENT("菜品 不能為空!");
}
try {
Integer orderId= orderService.createOrder(userId, dishesList);
if(orderId!=null){
return ServerResponse.createBySuccess(orderId);
}
} catch (Exception e) {
e.printStackTrace();
return ServerResponse.createByError("伺服器異常:" + e.getMessage());
}
return ServerResponse.createByError("建立訂單失敗");
}