Angularjs中$http以post请求通过消息体传递参数的实现方法

本文实例讲述了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

posted @ 2016-12-21 09:48  Mundo Novo  阅读(3945)  评论(0编辑  收藏  举报