Angularjs中,$http以post在消息體中傳遞參數,需要做以下修改,以確保消息體傳遞參數的正確性。 一、在聲明應用的時候進行設置: 1 var httpPost = function ($httpProvider) { 2 /******************************** ...
Angularjs中,$http以post在消息體中傳遞參數,需要做以下修改,以確保消息體傳遞參數的正確性。
一、在聲明應用的時候進行設置:1 var httpPost = function ($httpProvider) { 2 /******************************************* 3 說明:$http的post提交時,糾正消息體 4 參考:http://victorblog.com/2012/12/20/make-angularjs-http-service-behave-like-jquery-ajax/ 5 ********************************************/ 6 // Use x-www-form-urlencoded Content-Type 7 $httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8'; 8 /* 9 * The workhorse; converts an object to x-www-form-urlencoded serialization. 10 * @param {Object} obj 11 * @return {String} 12 */ 13 var param = function (obj) { 14 var query = '', name, value, fullSubName, subName, subValue, innerObj, i; 15 16 for (name in obj) { 17 value = obj[name]; 18 19 if (value instanceof Array) { 20 for (i = 0; i < value.length; ++i) { 21 subValue = value[i]; 22 fullSubName = name + '[' + i + ']'; 23 innerObj = {}; 24 innerObj[fullSubName] = subValue; 25 query += param(innerObj) + '&'; 26 } 27 } else if (value instanceof Object) { 28 for (subName in value) { 29 subValue = value[subName]; 30 fullSubName = name + '[' + subName + ']'; 31 innerObj = {}; 32 innerObj[fullSubName] = subValue; 33 query += param(innerObj) + '&'; 34 } 35 } else if (value !== undefined && value !== null) 36 query += encodeURIComponent(name) + '=' + encodeURIComponent(value) + '&'; 37 } 38 39 return query.length ? query.substr(0, query.length - 1) : query; 40 }; 41 42 // Override $http service's default transformRequest 43 $httpProvider.defaults.transformRequest = [ 44 function (data) { 45 return angular.isObject(data) && String(data) !== '[object File]' ? param(data) : data; 46 } 47 ]; 48 }; 49 50 var ngApp = angular.module('wtApp', ['ngCookies'], httpPost);
二、調用$http post
1 $http({ 2 method: 'POST', 3 url: 'GetData.ashx', 4 params: { id: '1002' },//params作為url的參數 5 data: { keyName: 'qubernet' }//作為消息體參數 6 }, function (data) { 7 8 });