angularjs 的post 請求該如何調用?
簡單示例:
// post 攜帶參數訪問 $http({ method:'post', url:postUrl, data:{name:"aaa",id:1,age:20} }).success(function(req){ console.log(req); });
上面這種方法還是有些問題,攜帶的參數並不能發送給后台。結果為null,這是因為要轉換為 form data:
可以參考:
https://blog.csdn.net/fengzijinliang/article/details/51897991
解決示例:
$http({ method:'post', url:postUrl, data:{name:"aaa",id:1,age:20}, headers:{'Content-Type': 'application/x-www-form-urlencoded'}, transformRequest: function(obj) { var str = []; for(var p in obj){ str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p])); } return str.join("&"); } }).success(function(req){ console.log(req); });