在下面的代码中,AngularJS $http方法调用URL,并提交xsrf对象作为“Request Payload”(在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() {}
});

当前回答

使用AngularJS的$http服务,并使用它的post方法或配置$http函数。

其他回答

从AngularJS v1.4.0开始,就有一个内置的$httpParamSerializer服务,它可以根据文档页面上列出的规则将任何对象转换为HTTP请求的一部分。

它可以这样使用:

$http.post('http://example.com', $httpParamSerializer(formDataObj)).
    success(function(data){/* response status 200-299 */}).
    error(function(data){/* response status 400-999 */});

请记住,对于正确的表单post, Content-Type头必须更改。要对所有POST请求全局执行此操作,可以使用以下代码(取自Albireo的half-answer):

$http.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded";

为了只针对当前post,需要修改request-object的headers属性:

var req = {
 method: 'POST',
 url: 'http://example.com',
 headers: {
   'Content-Type': 'application/x-www-form-urlencoded'
 },
 data: $httpParamSerializer(formDataObj)
};

$http(req);
var fd = new FormData();
    fd.append('file', file);
    $http.post(uploadUrl, fd, {
        transformRequest: angular.identity,
        headers: {'Content-Type': undefined}
    })
    .success(function(){
    })
    .error(function(){
    });

请付款! https://uncorkedstudios.com/blog/multipartformdata-file-upload-with-angularjs

作为一种变通方法,你可以简单地让接收POST的代码响应application/json数据。对于PHP,我添加了下面的代码,允许我以表单编码或JSON形式POST到它。

//handles JSON posted arguments and stuffs them into $_POST
//angular's $http makes JSON posts (not normal "form encoded")
$content_type_args = explode(';', $_SERVER['CONTENT_TYPE']); //parse content_type string
if ($content_type_args[0] == 'application/json')
  $_POST = json_decode(file_get_contents('php://input'),true);

//now continue to reference $_POST vars as usual

使用AngularJS的$http服务,并使用它的post方法或配置$http函数。

你唯一需要改变的是在创建$http对象时使用属性"params"而不是"data":

$http({
   method: 'POST',
   url: serviceUrl + '/ClientUpdate',
   params: { LangUserId: userId, clientJSON: clients[i] },
})

在上面的例子中,客户端[i]只是JSON对象(没有以任何方式序列化)。如果你使用“params”而不是“data”,angular会使用$httpParamSerializer: https://docs.angularjs.org/api/ng/service/$httpParamSerializer为你序列化对象