繁体   English   中英

带有JSON数据的Javascript HTTP POST

[英]Javascript HTTP POST with JSON data

我可以发送如下请求吗? 为参数分配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);

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

如果你想发送JSON,你必须:

  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数据。

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

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)); 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM