首頁 >web前端 >js教程 >Angularjs中$http以post請求透過訊息本體傳遞參數的實作方法

Angularjs中$http以post請求透過訊息本體傳遞參數的實作方法

高洛峰
高洛峰原創
2017-02-16 17:15:431365瀏覽

本文實例講述了Angularjs中$http以post請求透過訊息體傳遞參數的方法。分享給大家供大家參考,具體如下:

Angularjs中,$http以post在訊息體中傳遞參數,需要做以下修改,以確保訊息體傳遞參數的正確性。

一、在聲明應用的時候進行設定:

var httpPost = function($httpProvider) {
  /*******************************************
  说明:$http的post提交时,纠正消息体
  ********************************************/
  // 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 + &#39;[&#39; + i + &#39;]&#39;;
          innerObj = {};
          innerObj[fullSubName] = subValue;
          query += param(innerObj) + &#39;&&#39;;
        }
      } else if (value instanceof Object) {
        for (subName in value) {
          subValue = value[subName];
          fullSubName = name + &#39;[&#39; + subName + &#39;]&#39;;
          innerObj = {};
          innerObj[fullSubName] = subValue;
          query += param(innerObj) + &#39;&&#39;;
        }
      } else if (value !== undefined && value !== null)
        query += encodeURIComponent(name) + &#39;=&#39; + encodeURIComponent(value) + &#39;&&#39;;
    }
    return query.length ? query.substr(0, query.length - 1) : query;
  };
  // Override $http service&#39;s default transformRequest
  $httpProvider.defaults.transformRequest = [
    function(data) {
      return angular.isObject(data) && String(data) !== &#39;[object File]&#39; ? param(data) : data;
    }
  ];
};
var ngApp = angular.module(&#39;wtApp&#39;, [&#39;ngCookies&#39;], httpPost);

二、調用$http post

方法相關文章請關注PHP中文網!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn