如何将数据作为表单数据而不是请求有效负载发布? [英] How can I post data as form data instead of a request payload?
问题描述
在下面的代码中,AngularJS $http
方法调用 URL,并将 xsrf 对象作为请求负载"提交(如 Chrome 调试器网络选项卡中所述).jQuery $.ajax
方法执行相同的调用,但将 xsrf 作为表单数据"提交.
In the code below, the AngularJS $http
method calls the URL, and submits the xsrf object as a "Request Payload" (as described in the Chrome debugger network tab). The jQuery $.ajax
method does the same call, but submits xsrf as "Form Data".
如何让 AngularJS 将 xsrf 作为表单数据而不是请求负载提交?
How can I make AngularJS submit xsrf as form data instead of a request payload?
var url = 'http://somewhere.com/';
var xsrf = {fkey: 'xsrf key'};
$http({
method: 'POST',
url: url,
data: xsrf
}).success(function () {});
$.ajax({
type: 'POST',
url: url,
data: xsrf,
dataType: 'json',
success: function() {}
});
推荐答案
需要在传入的 $http 对象中添加以下行:
The following line needs to be added to the $http object that is passed:
headers: {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'}
并且传递的数据应该转换为 URL 编码的字符串:
And the data passed should be converted to a URL-encoded string:
> $.param({fkey: "key"})
'fkey=key'
所以你有类似的东西:
$http({
method: 'POST',
url: url,
data: $.param({fkey: "key"}),
headers: {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'}
})
来自:https://groups.google.com/forum/#!msg/angular/5nAedJ1LyO0/4Vj_72EZcDsJ
要使用 AngularJS V1.4 添加的新服务,请参阅
To use new services added with AngularJS V1.4, see
这篇关于如何将数据作为表单数据而不是请求有效负载发布?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!