1.ajax 发送get请求
<script src="js/vendor/jquery-3.3.1.min.js"></script>
<script type="text/javascript">
function save() {
var obj = {
item: "商品信息",
quantity: 11,
total_price: 22,
receiver_id: "赠予人id",
remark: "备注"
};
$.ajax({
type: "get",
url: "http://localhost/order/add",
contentType: "application/json; charset=utf-8",
data: obj,
traditional: true,
dataType: "json",
success: function(message) {
alert("hello");
}
});
}
</script>
值得注意的问题是:
1.data 直接传的是JSON对象,并没有将JSON对象转为JSON字符串
2.后台Spring直接通过@RequestParam 可以接收到get请求发的JSON对象,不能使用@RequestBody接收。
作者待解决的疑问:为啥在这里能够直接传JSON对象?
2.ajax 发送post请求
<script src="js/vendor/jquery-3.3.1.min.js"></script>
<script type="text/javascript">
function save() {
var obj = {
item: "商品信息"
};
$.ajax({
type: "post",
url: "http://localhost/order/add",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(obj),
traditional:true,
dataType: "json",
success: function(message) {
alert("hello");
}
});
}
</script>
值得注意的问题是:
1.传递JSON数据时,需要通过JSON.stringify()将JSON对象序列化成JSON字符串,才能传递到后台。
2.traditional属性为false时,即jquery会深度序列化参数对象,但后台的servlet api无法处理,因此需要将traditional设置为true防止深度序列化。
3.后台Spring通过@RequestBody接收到JSON字符串后进行反序列化,得到JSON对象。
如果是用@RequestParam接收,JSON字符串会被当成key值,value值为空。
@RequestBody和@RequestParam区别,参考:https://blog.csdn.net/xinluke/article/details/52710706