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