带有 JSON 数据的 Javascript HTTP POST

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18962799/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 13:52:02  来源:igfitidea点击:

Javascript HTTP POST with JSON data

javascripthttppost

提问by anaconda_wly

Can I send a request as below? With parameters being assigned with a JSON style object. I only get error. But when I use a REST client and choose RAW data, it's OK. I guess I must have written incorrect code. How to send raw JSON data in JavaScript? Could anyone help me?

我可以发送如下请求吗?使用 JSON 样式对象分配参数。我只得到错误。但是当我使用 REST 客户端并选择 RAW 数据时,就可以了。我想我一定写了不正确的代码。如何在 JavaScript 中发送原始 JSON 数据?有人可以帮助我吗?

xmlhttp = new XMLHttpRequest();
var url = "https://someURL";
xmlhttp.open("POST", url, true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.onreadystatechange = function () { //Call a function when the state changes.
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
        alert(xmlhttp.responseText);
    }
}
var parameters = {
    "username": "myname",
    "password": "mypass"
};
// Neither was accepted when I set with parameters="username=myname"+"&password=mypass" as the server may not accept that
xmlhttp.send(parameters);

回答by Quentin

No. The send()method can take a number of different argument types, but a plain object is not one of them (so it will probably end up having toString()being called on it and being turned into "[Object object]").

不。该send()方法可以采用许多不同的参数类型,但普通对象不是其中之一(因此它可能最终会toString()被调用并变成"[Object object]")。

If you want to send JSON then you must:

如果要发送 JSON,则必须:

  1. Say you are sending JSON: xmlhttp.setRequestHeader("Content-type", "application/json");
  2. Convert your JavaScript object to a string of JSON text: var parameters = JSON.stringify({"username":"myname","password":"mypass"});
  3. Be prepared to accept JSON instead of application/x-www-form-urlencoded data on the server side.
  1. 假设您要发送 JSON: xmlhttp.setRequestHeader("Content-type", "application/json");
  2. 将您的 JavaScript 对象转换为一串 JSON 文本: var parameters = JSON.stringify({"username":"myname","password":"mypass"});
  3. 准备好在服务器端接受 JSON 而不是 application/x-www-form-urlencoded 数据。


Also note that, since you are using an absoluteURI, you may run into cross domain issues.

另请注意,由于您使用的是绝对URI,您可能会遇到跨域问题

回答by mhdnp1234

xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST", AjaxURL, true);
xmlhttp.onreadystatechange = function () { //Call a function when the state changes.
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
cb(xmlhttp.responseText);               
}
};
xmlhttp.send(JSON.stringify(Idata));