jquery中$.ajax和angularjs中$http 使用restful api post提交數據時的不一致的解決方法

本文討論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);
        }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章