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<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']中.


 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM