如何在jQuery Ajax中设置原始主体?

Ita*_*vka 39 javascript jquery post

我需要发送一个JSON字符串作为POST请求的主体,而不是发送键/值对列表.
我使用jQuery的$ .ajax函数发出这个POST请求.
我该如何正确设置?

当我说JSON字符串时,我的意思是:{action:'x',params:['a','b','c']}.

这就是我在服务器上使用PHP中的这个JSON字符串的方法:

var_dump(json_decode(file_get_contents('php://input')));
Run Code Online (Sandbox Code Playgroud)

结果是:

stdClass Object
    action = x
    params = Array
        (
    0 = a
    1 = b
    2 = c
        )
Run Code Online (Sandbox Code Playgroud)

pet*_*ete 95

尝试:

$.ajax('url',{
    'data': JSON.stringify(yourJSONObject), //{action:'x',params:['a','b','c']}
    'type': 'POST',
    'processData': false,
    'contentType': 'application/json' //typically 'application/x-www-form-urlencoded', but the service you are calling may expect 'text/json'... check with the service to see what they expect as content-type in the HTTP header.
});
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助,

皮特

  • 'contentType':'application/json'在我看来. (6认同)

Raf*_*fay 5

如果您不指定密钥,我认为它将作为没有密钥的正文发布,例如

$.ajax({
data:JSON.stringify({action:'x',params:['a','b','c']})
});
Run Code Online (Sandbox Code Playgroud)