小编典典

使用JSON使XmlHttpRequest POST

ajax

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

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

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

这是我的JSON:

{
   email: "hello@user.com",
   response: {
       name: "Tester"
   }
}

阅读 903

收藏
2020-07-26

共1个答案

小编典典

如果正确使用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" } }));
2020-07-26