Javascript : Send JSON Object with Ajax?

2022-08-30 02:23:05

这可能吗?

xmlHttp.send({
    "test" : "1",
    "test2" : "2",
});

也许与:标题为:?:content typeapplication/json

xmlHttp.setRequestHeader('Content-Type', 'application/json')

否则,我可以使用:

xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')

然后是 JSON 对象并在参数中发送它,但如果可能的话,以这种方式发送它会很酷。JSON.stringify


答案 1

使用jQuery:

$.post("test.php", { json_string:JSON.stringify({name:"John", time:"2pm"}) });

没有jQuery:

var xmlhttp = new XMLHttpRequest();   // new HttpRequest instance 
xmlhttp.open("POST", "/json-handler");
xmlhttp.setRequestHeader("Content-Type", "application/json");
xmlhttp.send(JSON.stringify({name:"John Rambo", time:"2pm"}));

答案 2

如果您没有使用jQuery,请确保:

var json_upload = "json_name=" + JSON.stringify({name:"John Rambo", time:"2pm"});
var xmlhttp = new XMLHttpRequest();   // new HttpRequest instance 
xmlhttp.open("POST", "/file.php");
xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlhttp.send(json_upload);

对于 php 接收端:

 $_POST['json_name']