本文實例講述了Angularjs中$http以post請求通過消息體傳遞參數的方法。分享給大家供大家參考,具體如下:
Angularjs中,$http以post在消息體中傳遞參數,需要做以下修改,以確保消息體傳遞參數的正確性。
一、在聲明應用的時候進行設置:
1 var httpPost = function($httpProvider) { 2 /******************************************* 3 說明:$http的post提交時,糾正消息體 4 ********************************************/ 5 // Use x-www-form-urlencoded Content-Type 6 $httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8'; 7 /* 8 * The workhorse; converts an object to x-www-form-urlencoded serialization. 9 * @param {Object} obj 10 * @return {String} 11 */ 12 var param = function(obj) { 13 var query = '', name, value, fullSubName, subName, subValue, innerObj, i; 14 for (name in obj) { 15 value = obj[name]; 16 if (value instanceof Array) { 17 for (i = 0; i < value.length; ++i) { 18 subValue = value[i]; 19 fullSubName = name + '[' + i + ']'; 20 innerObj = {}; 21 innerObj[fullSubName] = subValue; 22 query += param(innerObj) + '&'; 23 } 24 } else if (value instanceof Object) { 25 for (subName in value) { 26 subValue = value[subName]; 27 fullSubName = name + '[' + subName + ']'; 28 innerObj = {}; 29 innerObj[fullSubName] = subValue; 30 query += param(innerObj) + '&'; 31 } 32 } else if (value !== undefined && value !== null) 33 query += encodeURIComponent(name) + '=' + encodeURIComponent(value) + '&'; 34 } 35 return query.length ? query.substr(0, query.length - 1) : query; 36 }; 37 // Override $http service's default transformRequest 38 $httpProvider.defaults.transformRequest = [ 39 function(data) { 40 return angular.isObject(data) && String(data) !== '[object File]' ? param(data) : data; 41 } 42 ]; 43 }; 44 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 });
原文地址:http://www.jb51.net/article/89932.htm