本文介绍了AngularJs $ http.post()不发送数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我拉我的头发 - 任何人都可以告诉我为什么下面的语句不后的数据发送到指定的网址是什么? URL被称为但是当我打印$ _ POST在服务器上 - 我得到一个空数组。如果我将它添加到数据之前在控制台打印的消息 - 它显示了正确的内容。
$ http.post('请求的URL,{消息:消息});
我也与数据串(具有相同效果),试了一下
$ http.post('请求的URL,消息=+消息);
这似乎是工作,当我在下面的格式使用它:
$ HTTP({
方法:POST,
网址:'请求的URL,
数据:消息=+消息,
标题:{内容类型:应用程序/ x-WWW的形式urlen codeD'}
});
但有与$ http.post()做这件事的一个方法 - 我总是有包括以头为它工作?我认为,上述内容类型指定发送的数据格式,但我可以把它作为JavaScript对象?
解决方案
我不得不使用asp.net MVC和的解决方案
Works like a charm.
CODE
// Your app's root module...
angular.module('MyModule', [], function($httpProvider) {
// Use x-www-form-urlencoded Content-Type
$httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';
/**
* The workhorse; converts an object to x-www-form-urlencoded serialization.
* @param {Object} obj
* @return {String}
*/
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;
};
// Override $http service's default transformRequest
$httpProvider.defaults.transformRequest = [function(data) {
return angular.isObject(data) && String(data) !== '[object File]' ? param(data) : data;
}];
});
这篇关于AngularJs $ http.post()不发送数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!