【问题标题】:How to set the raw body in jQuery Ajax?如何在 jQuery Ajax 中设置原始正文?
【发布时间】:2012-01-31 17:43:04
【问题描述】:

我需要发送一个 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
        )

【问题讨论】:

  • 我现在明白了 - 你想以某种方式用你选择的 json 字符串实际替换 xhr 请求的正文?这里不知道 - 希望专家会过来说这是否可能

标签: javascript jquery post


【解决方案1】:

试试:

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

希望对你有帮助,

皮特

【讨论】:

  • 'contentType': 'application/json' 在我看来。
  • 你的语法很奇怪——见api.jquery.com/jquery.ajax——但 processData 确实可以完成这项工作。
  • 我的句法也是7岁。 :)
【解决方案2】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-09-21
    • 2018-12-05
    • 1970-01-01
    • 2012-05-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多