您的位置:首页 > 理论基础 > 计算机网络

AngularJs的$http发送POST请求,php无法接收Post的数据解决方案

2016-02-27 17:40 851 查看
最近在使用AngularJs+Php开发中遇到php后台无法接收到来自AngularJs的数据,在网上也有许多解决方法,却都点到即止.多番摸索后记录下解决方法:
tips:当前使用的AngularJs版本为v1.5.0-rc.0

原因分析:

在使用jquery的时候进行post请求的时候很简单.

$.ajax({
type: 'POST',
url:'process.php',
data: formData,
dataType: 'json',
success: function(result){
//do something
}
});


对这个传输的数据我们一般会直接使用serialize()或使用serializeArray()处理后再传输,但在发送post请求时jquery会把这个对象转换为字符串后再发送,类似"a=123&b=456".
而AngularJs传输的是一个Json数据而不是一个转换后的字符串,在php端接收的时候不能直接使用$_POST方式接收.这样是获取不到数据的.
$POST方式只能接收Content-Type: application/x-www-form-urlencoded提交的数据,也就是表单提交的数据.
但可以使用file_get_contents("php://input")接收,对于没有没有指定Content-Type的Post数据也是可以接收到的,此时获取到的是个字符串还需要再转换才能变成我们想要的数据格式.这样无疑增加了工作量.

解决方案:

1.引用JQuery,使用JQuery的$.param()方法序列化参数后传递

$http({
method  : 'POST',
url: 'process.php',
data: $.param($scope.formData), //序列化参数
headers: { 'Content-Type': 'application/x-www-form-urlencoded' } )
})  


2.使用file_get_contents("php://input")获取再处理

$input = file_get_contents("php://input",true);
echo $input;  


3.修改Angular的$httpProvider的默认处理(参考:http://victorblog.com/2012/12/20/make-angularjs-http-service-behave-like-jquery-ajax/)

// Your app's root module...
angular.module('MyModule', [], function($httpProvider) {
// Use x-www-form-urlencoded Content-Type
$httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';

/**
* The workhorse; converts an object to x-www-form-urlencoded serialization.
* @param {Object} obj
* @return {String}
*/
var param = function(obj) {
var query = '', name, value, fullSubName, subName, subValue, innerObj, i;

for(name in obj) {
value = obj[name];

if(value instanceof Array) {
for(i=0; i<value.length; ++i) {
subValue = value[i];
fullSubName = name + '[' + i + ']';
innerObj = {};
innerObj[fullSubName] = subValue;
query += param(innerObj) + '&';
}
}
else if(value instanceof Object) {
for(subName in value) {
subValue = value[subName];
fullSubName = name + '[' + subName + ']';
innerObj = {};
innerObj[fullSubName] = subValue;
query += param(innerObj) + '&';
}
}
else if(value !== undefined && value !== null)
query += encodeURIComponent(name) + '=' + encodeURIComponent(value) + '&';
}

return query.length ? query.substr(0, query.length - 1) : query;
};

// Override $http service's default transformRequest
$httpProvider.defaults.transformRequest = [function(data) {
return angular.isObject(data) && String(data) !== '[object File]' ? param(data) : data;
}];
});


$http({
method:"POST",
url:"/api/login.php",
data:$scope.Account
});


补:

php获取时也可通过
$GLOBALS
[
'HTTP_RAW_POST_DATA'
]获取POST提交的原始数据.
但$GLOBALS['HTTP_RAW_POST_DATA']中是否保存POST过来的数据取决于centent-Type的设置,即POST数据时 必须显式示指明Content-Type: application/x-www-form-urlencoded,POST的数据才会存放到 $GLOBALS['HTTP_RAW_POST_DATA']中.



                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: