本文讨论post
本质
1 $.ajax 是 把 json 使用$.param处理 。使用 application/x-www-form-urlencoded
2 $http会 使用JOSN.stringify来处理。使用 application/json
所以:它们发送的数据就会不一样
1 代码像这样 “a=1&b=2”
2 代码像这样 “{a:1,b:2}”
解决
数据格式的不统一,则要求我们要分别做处理,或者把它统一起来
1 后端分别处理
2 前端统一数据格式
使用$.ajax的格式,$http给的方案是
$http({
url: url,
method: 'POST',
data: $httpParamSerializerJQLike(myData),
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
});
在用restful api时, jquery也要写成
$.ajax({
url:url,
type:'POST',
data:JSON.stringify({"id":1,"name":"xx"}),
contentType:'application/json; charset=utf-8',
dataType:'json'
})
java 接受post的 json要
BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream(),"utf-8"));
String line = null;
StringBuilder str = new StringBuilder();
while ((line = br.readLine()) != null) {
str.append(line);
}