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

标签 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')));

结果:

stdClass Object
    action = x
    params = Array
        (
    0 = a
    1 = b
    2 = c
        )

最佳答案

尝试:

$.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.
});

希望对您有所帮助,

皮特

关于javascript - 如何在 jQuery Ajax 中设置原始主体?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9084296/

相关文章:

c++ - LibCurl 似乎逃脱了我的 POSTFIELDS

javascript - 在 JavaScript 中等待两个异步命令

jquery - 如何通过 jQuery addClass() 使框阴影淡入淡出

javascript - 为什么 <div> 不移动?

javascript - 使用 jquery 修改列表中的第 n 个 li

jquery - 部分页面更新后打印元素背景 css 未被覆盖

vb.net - 在 VB.net 中加载 GET/POST 请求的结果

php - 如何使用 jQuery 和 POST 发送电子邮件

javascript - 如何使用 Javascript 填充选择框

javascript - 为什么 $route.current.params 和 $routeParams 不同?