[英]Javascript HTTP POST with JSON data
Can I send a request as below? 我可以发送如下请求吗? With parameters being assigned with a JSON style object.
为参数分配JSON样式对象。 I only get error.
我只得到错误。 But when I use a REST client and choose RAW data, it's OK.
但是当我使用REST客户端并选择RAW数据时,没关系。 I guess I must have written incorrect code.
我想我必须写错了代码。 How to send raw JSON data in JavaScript?
如何在JavaScript中发送原始JSON数据? Could anyone help me?
谁能帮助我?
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);
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,你必须:
xmlhttp.setRequestHeader("Content-type", "application/json");
xmlhttp.setRequestHeader("Content-type", "application/json");
var parameters = JSON.stringify({"username":"myname","password":"mypass"});
var parameters = JSON.stringify({"username":"myname","password":"mypass"});
Also note that, since you are using an absolute URI, you may run into cross domain issues . 另请注意,由于您使用的是绝对 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.