使用JSON使XmlHttpRequest POST

如何使用香草JS发出AJAX POST请求以发送JSON数据。

我知道content-type是url形式编码的,并且不支持嵌套的JSON。

有什么方法可以使用普通旧JS中的嵌套JSON发出这样的POST请求。我已经尝试过在SO上找到的各种序列化方法,但是它们都将JSON扁平化为一种格式。

这是我的JSON:

{

email: "hello@user.com",

response: {

name: "Tester"

}

}

回答:

如果正确使用JSON,则可以嵌套对象而不会出现任何问题:

var xmlhttp = new XMLHttpRequest();   // new HttpRequest instance 

var theUrl = "/json-handler";

xmlhttp.open("POST", theUrl);

xmlhttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8");

xmlhttp.send(JSON.stringify({ "email": "hello@user.com", "response": { "name": "Tester" } }));

以上是 使用JSON使XmlHttpRequest POST 的全部内容, 来源链接: utcz.com/qa/428820.html

回到顶部