angularjs中$http模块POST请求request payload转form data

时间:2022-08-22 17:24:59

angularjs发起$http.post请求:

代码如下:

 $http({
method
:'post',
url
:'post.php',
data
:{name:"aaa",id:1,age:20}
}).success(function(req){
console
.log(req);
})

运行结果(chrome→network):

angularjs中$http模块POST请求request payload转form data

这样的话在PHP中用$_POST是取不到的。

解决方案:

1.配置$httpProvider:

 var myApp = angular.module('app',[]);
myApp
.config(function($httpProvider){

$httpProvider
.defaults.transformRequest = function(obj){
var str = [];
for(var p in obj){
str
.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
}
return str.join("&");
}

$httpProvider
.defaults.headers.post = {
'Content-Type': 'application/x-www-form-urlencoded'
}

});

2.在post中配置:

 $http({
method
:'post',
url
:'post.php',
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);
})

运行结果(chrome→network):

angularjs中$http模块POST请求request payload转form data

至此成功换成form data;

3.PHP中放弃$_POST;

$rawpostdata = file_get_contents("php://input");
$post
= json_decode($rawpostdata, true);
//传的数据都在$post中了;

<!--End of the article-->