Javascript HTTP POST with JSON data
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);
No.send()
方法可以采用许多不同的参数类型,但普通对象不是其中之一(因此它最终可能会toString()
被调用并变成 "[Object object]"
)。
如果要发送 JSON,则必须:
- 假设您正在发送 JSON:
xmlhttp.setRequestHeader("Content-type", "application/json");
- 将 JavaScript 对象转换为 JSON 文本字符串:
var parameters = JSON.stringify({"username":"myname","password":"mypass"});
- 准备好在服务器端接受JSON而不是application/x-www-form-urlen编码数据。
另请注意,由于使用的是绝对 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));
相关文章:
- 使用$http的angular js中的JSON数据-data.push()
- 自定义筛选器不'我不使用django数据表视图创建的ajax.data.Json
- Highchart and json data
- 一个data.json被多个源访问和更改
- javascript foreach on array / json data 但按最新日期排序
- Jquery POST JSON data to Python backend
- JSON Data using ember.js
- Angularjs on JSON data
- Javascript HTTP POST with JSON data
- javascript Highcharts JSON data to HTML table
- Formatting response JSON data using AngularJS & ExpressJ
- 饼图不适用于使用AngularJS和nvd3的Json Data
- POST JSON data with cURL
- HTML5 localStorage (XML/JSON data)
- Angularjs json data
- Accessing JSON Data NativeScript
- 在变量(json data)内循环
- Load json-data into Highchart
- console.log JSON data?
- 没有json-data的ajax跨域请求