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

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

这篇文章主要介绍了AngularJs的$http发送POST请求,php无法接收Post的数据的问题及解决方案,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下

最近在使用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
 $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']中.

总结

以上就是AngularJs的$http发送POST请求,php无法接收Post的数据问题及解决方案的详细内容,更多请关注易知道|edz.cc其它相关文章!

推荐阅读