我如何将数据作为表单数据而不是请求负载发布?

15 浏览
0 Comments

我如何将数据作为表单数据而不是请求负载发布?

在下面的代码中,AngularJS $http 方法调用URL,并将xsrf对象作为“请求负载”提交(如Chrome调试器网络选项卡中所描述的)。jQuery $.ajax 方法执行相同的调用,但以“表单数据”的形式提交xsrf。

我怎样才能让AngularJS将xsrf作为表单数据而不是请求负载提交?

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() {}
});

admin 更改状态以发布 2023年5月23日
0
0 Comments

如果您不想在解决方案中使用jQuery,您可以尝试这个。解决方案来源于这里 https://stackoverflow.com/a/1714899/1784301

$http({
    method: 'POST',
    url: url,
    headers: {'Content-Type': 'application/x-www-form-urlencoded'},
    transformRequest: function(obj) {
        var str = [];
        for(var p in obj)
        str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
        return str.join("&");
    },
    data: xsrf
}).success(function () {});

0
0 Comments

需要在传递的$http对象中添加以下代码:

headers: {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'}

并且传递的数据应该被转换为URL编码的字符串:

> $.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中添加的新服务,请参见:

0