解决angularjs post方式提交时,获取不到参数
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
| angular.module('MyModule', [], function ($httpProvider) { $httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';
var param = function (obj) { var query = '', name, value, fullSubName, subName, subValue, innerObj, i;
for (name in obj) { value = obj[name];
if (value instanceof Array) { for (i = 0; i < value.length; ++i) { subValue = value[i]; fullSubName = name + '[' + i + ']'; innerObj = {}; innerObj[fullSubName] = subValue; query += param(innerObj) + '&'; } } else if (value instanceof Object) { for (subName in value) { subValue = value[subName]; fullSubName = name + '[' + subName + ']'; innerObj = {}; innerObj[fullSubName] = subValue; query += param(innerObj) + '&'; } } else if (value !== undefined && value !== null) query += encodeURIComponent(name) + '=' + encodeURIComponent(value) + '&'; }
return query.length ? query.substr(0, query.length - 1) : query; };
$httpProvider.defaults.transformRequest = [function (data) { return angular.isObject(data) && String(data) !== '[object File]' ? param(data) : data; } ]; });
|
将这段代码添加到指定的模块上,作用是将Content-Type
请求方式由 application/json
变为 'application/x-www-form-urlencoded;charset=utf-8
。
1 2 3 4 5 6 7 8 9 10
| $scope.save = function () { $http.post(location.href + "?action=Save", { aaa: "1111", bbb: "2222" }).success(function (r) { alert(r); }).error(function () {
}); }
|
这样后台就能正常的获取参数了