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

 

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

原因分析:

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

1
2
3
4
5
6
7
8
9
$.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()方法序列化参数后传递

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

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

1
2
$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/)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
// 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'default transformRequest
  $httpProvider.defaults.transformRequest = [function(data) {
    return angular.isObject(data) && String(data) !== '[object File]' ? param(data) : data;
  }];
});
1
2
3
4
5
$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']中.


作  者:浮云也是种寂寞 
出  处:http://www.cnblogs.com/summit7ca/ 
版权声明:本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接。 
若您觉得这篇文章还不错请点击下右下角的推荐,有了您的支持才能激发作者更大的写作热情,非常感谢。

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

原因分析:

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

1
2
3
4
5
6
7
8
9
$.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()方法序列化参数后传递

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

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

1
2
$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/)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
// 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'default transformRequest
  $httpProvider.defaults.transformRequest = [function(data) {
    return angular.isObject(data) && String(data) !== '[object File]' ? param(data) : data;
  }];
});
1
2
3
4
5
$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']中.