[英]XMLHttpRequest Posting empty body
When I try to post some data to my backend API service I use the XMLHttpRequest
object, but when I try to send the data with ajax.send
it sent nothing to the server 当我尝试将一些数据发布到后端API服务时,我使用
XMLHttpRequest
对象,但是当我尝试使用ajax.send
发送数据时,它什么也没有发送到服务器
Code snipper: 代码窃听器:
ajax = new XMLHttpRequest();
ajax.open("POST", "https://someapi.com",true);
ajax.send({
name: "Name",
phone: "123468375698563897569575863"
});
ajax.onreadystatechange = function(){
if(ajax.readyState==4){
JSONback = JSON.parse(ajax.response);
console.log(JSONback);
}
};
You cannot directly send a JS object over the wire. 您不能直接通过网络发送JS对象。
You need to convert it to a string first, just like you need to parse it when you're getting it back. 您需要先将其转换为字符串,就像在取回它时需要对其进行解析一样。
ajax = new XMLHttpRequest();
ajax.open("POST", "https://balbalbal.com", true);
ajax.send(
JSON.stringify({
name: "Name",
phone: "123468375698563897569575863"
})
);
ajax.onreadystatechange = function(){
if(ajax.readyState==4){
JSONback = JSON.parse(ajax.response);
console.log(JSONback);
}
};
The simplest PHP test code on the server side would be: 服务器端最简单的PHP测试代码是:
<?php
echo file_get_contents('php://input');
?>
And here is a slightly more advanced example that will decode it, add a new field and send it back: 这是一个稍微高级的示例,它将对其进行解码,添加新字段并将其发送回:
<?php
$json = file_get_contents('php://input');
$object = json_decode($json);
$object->id = 123;
echo json_encode($object);
?>
You need to: 你需要:
Such: 这样:
var data = {
name: "Name",
phone: "123468375698563897569575863"
};
var json = JSON.stringify(data);
var ajax = new XMLHttpRequest();
ajax.open("POST", "https://balbalbal.com", true);
ajax.setRequestHeader("Content-Type", "application/json");
ajax.send(json);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.