Angularjs中$http以post请求通过消息体传递参数

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

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值