【译】让ng的$http服务与jQuerr.ajax()一样易用

发布时间:2019-06-10 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了【译】让ng的$http服务与jQuerr.ajax()一样易用脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

@H_406_2@作者zeke
很多ng的初学者都有这样的困惑:为什么$http的service例如$http.post(),明明与jQuery的$.post()方法类似,却不可以直接换用,例如:

(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)无法解读这样的数据。

好在周到的ng开发者们提供了$http的hooks使得我们可以强制以 x-www-form-urlencoded 发送数据,关于这点很多人提供了解决办法,但都不太理想,因为你不得不去修改你的服务器代码或者$http的代码。介于此,我给出了可能是最优的解决方案,前后端的代码均无需修改:

// 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方法无法使用。

脚本宝典总结

以上是脚本宝典为你收集整理的【译】让ng的$http服务与jQuerr.ajax()一样易用全部内容,希望文章能够帮你解决【译】让ng的$http服务与jQuerr.ajax()一样易用所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。