最近在使用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 $http({ 2 method : ‘POST‘, 3 url: ‘process.php‘, 4 data: $.param($scope.formData), //序列化参数 5 headers: { ‘Content-Type‘: ‘application/x-www-form-urlencoded‘ } ) 6 })
$input = file_get_contents("php://input",true); echo $input;
1 // Your app‘s root module... 2 angular.module(‘MyModule‘, [], function($httpProvider) { 3 // Use x-www-form-urlencoded Content-Type 4 $httpProvider.defaults.headers.post[‘Content-Type‘] = ‘application/x-www-form-urlencoded;charset=utf-8‘; 5 6 /** 7 * The workhorse; converts an object to x-www-form-urlencoded serialization. 8 * @param {Object} obj 9 * @return {String} 10 */ 11 var param = function(obj) { 12 var query = ‘‘, name, value, fullSubName, subName, subValue, innerObj, i; 13 14 for(name in obj) { 15 value = obj[name]; 16 17 if(value instanceof Array) { 18 for(i=0; i<value.length; ++i) { 19 subValue = value[i]; 20 fullSubName = name + ‘[‘ + i + ‘]‘; 21 innerObj = {}; 22 innerObj[fullSubName] = subValue; 23 query += param(innerObj) + ‘&‘; 24 } 25 } 26 else if(value instanceof Object) { 27 for(subName in value) { 28 subValue = value[subName]; 29 fullSubName = name + ‘[‘ + subName + ‘]‘; 30 innerObj = {}; 31 innerObj[fullSubName] = subValue; 32 query += param(innerObj) + ‘&‘; 33 } 34 } 35 else if(value !== undefined && value !== null) 36 query += encodeURIComponent(name) + ‘=‘ + encodeURIComponent(value) + ‘&‘; 37 } 38 39 return query.length ? query.substr(0, query.length - 1) : query; 40 }; 41 42 // Override $http service‘s default transformRequest 43 $httpProvider.defaults.transformRequest = [function(data) { 44 return angular.isObject(data) && String(data) !== ‘[object File]‘ ? param(data) : data; 45 }]; 46 });
这样处理后进行post的时候可直接传递一个JSON对象(此时后台可通过$_POST获取):
1 $http({ 2 method:"POST", 3 url:"/api/login.php", 4 data:$scope.Account 5 });
补:
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‘]中.
本博客为浮云也是种寂寞原创,欢迎转载,但是必须保留本文的署名浮云也是种寂寞(包含链接)。如您有任何疑问,请给我留言。
AngularJs的$http发送POST请求,php无法接收Post的数据解决方案
原文:http://www.cnblogs.com/summit7ca/p/5223175.html