angularjs向后台传参,后台收不到数据

angularjs中封装了一个$http服务,用来请求远程资源

 

参见:HTTP API

 

其中封装过的$http.post和$http.get使用起来比较方便

 

后台是php,用$_POST['name']接收,一直接收不到代码,甚是奇怪

 

查阅文章所知,原来angular的$http服务和jquery的不一样

原文:

By default, jQuery transmits data using Content-Type: x-www-form-urlencoded and the familiar foo=bar&baz=moe serialization. AngularJS, however, transmits data using Content-Type: application/json and { "foo": "bar", "baz": "moe" } JSON serialization, which unfortunately some Web server languages—notably PHP—do not unserialize natively.

大意:

jquery传输数据用的Content-Type是:x-www-form-urlencoded,类似url传参,而angularJS的Content-Type是 application/json,是使用JSON序列化传参,而PHP正好默认不会接收后者。

根据老外的提议,改服务端代码当然也可以,但是还是$_POST用的习惯,所以就将angular的传参方式改为jquery的方式,下面是代码,放在主module里就可以了

// 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;
  }];
});

Done!

 

原文链接:Link

 

posted @ 2015-03-16 10:32  savokiss  阅读(2398)  评论(0编辑  收藏  举报