【譯】讓ng的$http服務與jQuerr.ajax()同樣易用

做者zeke
不少ng的初學者都有這樣的困惑:爲何$http的service例如$http.post(),明明與jQuery的$.post()方法相似,卻不能夠直接換用,例如:json

(function($) {
  jQuery.post('/endpoint', { foo: 'bar' }).success(function(response) {
    // ...
  });
})(jQuery);

這樣的代碼在ng中並不會正常運行。後端

var MainCtrl = function($scope, $http) {
  $http.post('/endpoint', { foo: 'bar' }).success(function(response) {
    // ...
  });
};

你會發現你的服務器並未收到{ foo: 'bar' } 的參數服務器

這個區別在於jQuery和ng在傳輸data時是否對其序列化。根本緣由在於你的服務器沒法解讀ng傳遞過來的原始數據。jQ默認使用Content-Type: x-www-form-urlencoded 將data轉碼爲foo=bar&baz=moe 的形式。ng則是Content-Type: application/json 來發送{ "foo": "bar", "baz": "moe" } 的JSON串,這使得服務器端(尤爲是PHP)沒法解讀這樣的數據。app

好在周到的ng開發者們提供了$http的hooks使得咱們能夠強制以 x-www-form-urlencoded 發送數據,關於這點不少人提供瞭解決辦法,但都不太理想,由於你不得不去修改你的服務器代碼或者$http的代碼。介於此,我給出了多是最優的解決方案,先後端的代碼均無需修改:ide

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

不要使用jQuery.param()代替上面的param()方法,它將會形成ng的$resource方法沒法使用。post

相關文章
相關標籤/搜索