gpt4 book ai didi

AngularJs $http.post() 不发送数据

转载 作者:行者123 更新时间:2023-12-03 03:59:24 24 4
gpt4 key购买 nike

谁能告诉我为什么下面的语句没有将post数据发送到指定的url? url 被调用,但在服务器上,当我打印 $_POST 时 - 我得到一个空数组。如果我在将消息添加到数据之前在控制台中打印消息 - 它会显示正确的内容。

$http.post('request-url',  { 'message' : message });

我也尝试过将数据作为字符串(具有相同的结果):

$http.post('request-url',  "message=" + message);

当我以以下格式使用它时,它似乎可以工作:

$http({
method: 'POST',
url: 'request-url',
data: "message=" + message,
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
});

但是有没有办法用 $http.post() 来做到这一点 - 我是否总是必须包含 header 才能使其工作?我相信上述内容类型指定了发送数据的格式,但是我可以将其作为 javascript 对象发送吗?

最佳答案

我在使用 asp.net MVC 和 found the solution here 时遇到了同样的问题

There is much confusion among newcomers to AngularJS as to why the$http service shorthand functions ($http.post(), etc.) don’t appear tobe swappable with the jQuery equivalents (jQuery.post(), etc.)

The difference is in how jQuery and AngularJS serialize and transmit the data. Fundamentally, the problem lies with your server language of choice being unable to understand AngularJS’s transmission natively ... By default, jQuery transmits data using

Content-Type: x-www-form-urlencoded

and the familiar foo=bar&baz=moe serialization.

AngularJS,但是,使用传输数据

Content-Type: application/json 

and { "foo": "bar", "baz": "moe" }

JSON serialization, which unfortunately some Web server languages—notablyPHP—do not unserialize natively.

就像魅力一样。

代码

// 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() 不发送数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19254029/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com