JavaScript如何使用Ajax发送JSON对象?

16 浏览
0 Comments

JavaScript如何使用Ajax发送JSON对象?

这种方法有可能吗?

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

或许可以通过设置头部content type:application/json来实现:

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

不然我可以使用:

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

然后将JSON对象JSON.stringify并在参数中发送,但是如果有可能这样发送会很酷。

admin 更改状态以发布 2023年5月21日
0
0 Comments

如果您不使用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'] 

0
0 Comments

使用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"}));

0