angularjs採用類似jqery ajax模式發送請求

AngularJs使用$http模塊發送請求的時候,發送的格式是json格式的,和普通form表單格式的請求不同,後臺無法解析。

{"loginName":"18910474353","content":"測試測試"}

通過使用fiddler抓包,可以看出,普通的form發送的請求,格式如下:

loginName=18910474353&content=測試測試

並且,在請求頭header中,Content-Type的值爲:application/x-www-form-urlencoded;charset=utf-8

如果請求頭的Content-Type不是這個值,即便格式如上,後臺也不會收到值。

那麼,Angular中怎麼設置一下請求頭呢?

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

經過這樣設置後,我們再發送的請求,就是以form表單的形式發送的了。


參考文章:

Make AngularJS $http service behave like jQuery.ajax()


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章