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