Javascript 使用 JSON 进行 XmlHttpRequest POST
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/39519246/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Make XmlHttpRequest POST using JSON
提问by Akshay Khetrapal
How can I make an AJAX POST request sending JSON data using vanilla JS.
如何使用 vanilla JS 进行 AJAX POST 请求发送 JSON 数据。
I understand the content-type is url form encoded and it doesn't support nested JSONs.
我知道内容类型是 url 形式编码的,它不支持嵌套的 JSON。
Is there any way I can make such a POST request using nested JSON in plain old JS. I've tried the various serialize methods found here on SO but they all flatten my JSON into one format.
有什么方法可以在普通的旧 JS 中使用嵌套的 JSON 发出这样的 POST 请求。我已经尝试了在 SO 上找到的各种序列化方法,但它们都将我的 JSON 扁平化为一种格式。
Here's my JSON:
这是我的 JSON:
{
email: "[email protected]",
response: {
name: "Tester"
}
}
回答by Gilles Quenot
If you use JSON properly, you can have nested object without any issue :
如果您正确使用 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": "[email protected]", "response": { "name": "Tester" } }));