本文翻译自:AngularJs $http.post() does not send data
Could anyone tell me why the following statement does not send the post data to the designated url? 谁能告诉我为什么以下声明不会将发布数据发送到指定的网址? The url is called but on the server when I print $_POST - I get an empty array. 当我打印$ _POST时,在服务器上调用url - 我得到一个空数组。 If I print message in the console before adding it to the data - it shows the correct content. 如果我在将数据添加到数据之前在控制台中打印消息 - 它会显示正确的内容。
$http.post('request-url', { 'message' : message });
I've also tried it with the data as string (with the same outcome): 我也尝试将数据作为字符串(具有相同的结果):
$http.post('request-url', "message=" + message);
It seem to be working when I use it in the following format: 当我以下列格式使用它时,它似乎正在工作:
$http({
method: 'POST',
url: 'request-url',
data: "message=" + message,
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
});
but is there a way of doing it with the $http.post() - and do I always have to include the header in order for it to work? 但有没有办法用$ http.post()来做 - 并且我总是必须包含标题才能使它工作? I believe that the above content type is specifying format of the sent data, but can I send it as javascript object? 我相信上面的内容类型是指定发送数据的格式,但我可以将其作为javascript对象发送吗?
#1楼
参考:https://stackoom.com/question/1Imqr/AngularJs-http-post-不发送数据
#2楼
You can set the default "Content-Type" like this: 您可以像这样设置默认的“Content-Type”:
$http.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded";
About the data
format: 关于data
格式:
The $http.post and $http.put methods accept any JavaScript object (or a string) value as their data parameter. $ http.post和$ http.put方法接受任何JavaScript对象(或字符串)值作为其数据参数。 If data is a JavaScript object it will be, by default, converted to a JSON string. 如果data是JavaScript对象,则默认情况下它将转换为JSON字符串。
Try to use this variation 尝试使用此变体
function sendData($scope) {
$http({
url: 'request-url',
method: "POST",
data: { 'message' : message }
})
.then(function(response) {
// success
},
function(response) { // optional
// failed
});
}
#3楼
I had the same problem using asp.net MVC and found the solution here 我使用asp.net MVC遇到了同样的问题,并在此处找到了解决方案
There is much confusion among newcomers to AngularJS as to why the
$http
service shorthand functions ($http.post()
, etc.) don't appear to be swappable with the jQuery equivalents (jQuery.post()
, etc.) AngularJS的新手之间存在很多混淆,为什么$http
服务速记函数($http.post()
等)似乎不能与jQuery等价物交换(jQuery.post()
等)The difference is in how jQuery and AngularJS serialize and transmit the data. 不同之处在于jQuery和AngularJS如何序列化和传输数据。 Fundamentally, the problem lies with your server language of choice being unable to understand AngularJS's transmission natively ... By default, jQuery transmits data using 从根本上说,问题在于您选择的服务器语言本身无法理解AngularJS的传输...默认情况下, jQuery使用
Content-Type: x-www-form-urlencoded
and the familiar
foo=bar&baz=moe
serialization. 和熟悉的foo=bar&baz=moe
序列化。AngularJS , however, transmits data using 然而, AngularJS使用传输数据
Content-Type: application/json
and
{ "foo": "bar", "baz": "moe" }
和{ "foo": "bar", "baz": "moe" }
JSON serialization, which unfortunately some Web server languages— notably PHP —do not unserialize natively. JSON序列化,遗憾的是一些Web服务器语言 - 特别是PHP -本身没有反序列化。
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;
}];
});
#4楼
I know has accepted answer. 我知道已经接受了答案。 But, following might help to future readers, if the answer doesn't suit them for any reason. 但是,如果答案因任何原因不适合他们,以下可能会对未来的读者有所帮助。
Angular doesn't do ajax same as jQuery. Angular不像jQuery那样执行ajax。 While I tried to follow the guide to modify angular $httpprovider
, I encountered other problems. 虽然我试图按照指南修改角度$httpprovider
,但我遇到了其他问题。 Eg I use codeigniter in which $this->input->is_ajax_request()
function always failed (which was written by another programmer and used globally, so cant change) saying this was not real ajax request. 例如,我使用codeigniter,其中$this->input->is_ajax_request()
函数总是失败(由另一个程序员编写并全局使用,因此无法更改)说这不是真正的ajax请求。
To solve it, I took help of deferred promise . 为了解决这个问题,我接受了延期承诺的帮助。 I tested it in Firefox, and ie9 and it worked. 我在Firefox中测试了它,ie9并且它工作正常。
I have following function defined outside any of the angular code. 我在任何角度代码之外定义了跟随函数。 This function makes regular jquery ajax call and returns deferred/promise (I'm still learning) object. 这个函数定期进行jquery ajax调用并返回deferred / promise(我还在学习)对象。
function getjQueryAjax(url, obj){
return $.ajax({
type: 'post',
url: url,
cache: true,
data: obj
});
}
Then I'm calling it angular code using the following code. 然后我使用以下代码将其称为角度代码。 Please note that we have to update the $scope
manually using $scope.$apply()
. 请注意,我们必须使用$scope.$apply()
手动更新$scope
。
var data = {
media: "video",
scope: "movies"
};
var rPromise = getjQueryAjax("myController/getMeTypes" , data);
rPromise.success(function(response){
console.log(response);
$scope.$apply(function(){
$scope.testData = JSON.parse(response);
console.log($scope.testData);
});
}).error(function(){
console.log("AJAX failed!");
});
This may not be the perfect answer, but it allowed me to use jquery ajax calls with angular and allowed me to update the $scope
. 这可能不是完美的答案,但它允许我使用带有角度的jquery ajax调用并允许我更新$scope
。
#5楼
I have had a similar issue, and I wonder if this can be useful as well: https://stackoverflow.com/a/11443066 我有一个类似的问题,我想知道这是否也有用: https : //stackoverflow.com/a/11443066
var xsrf = $.param({fkey: "key"});
$http({
method: 'POST',
url: url,
data: xsrf,
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
})
Regards, 问候,
#6楼
I like to use a function to convert objects to post params. 我喜欢使用函数将对象转换为post params。
myobject = {'one':'1','two':'2','three':'3'}
Object.toparams = function ObjecttoParams(obj) {
var p = [];
for (var key in obj) {
p.push(key + '=' + encodeURIComponent(obj[key]));
}
return p.join('&');
};
$http({
method: 'POST',
url: url,
data: Object.toparams(myobject),
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
})