小编典典
使用POST方法以JSON格式发送和接收数据
// Sending and receiving data in JSON format using POST method
//
var xhr = new XMLHttpRequest();
var url = "url";
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
var json = JSON.parse(xhr.responseText);
console.log(json.email + ", " + json.password);
}
};
var data = JSON.stringify({"email": "hey@mail.com", "password": "101010"});
xhr.send(data);
使用GET方法以JSON格式发送接收数据
// Sending a receiving data in JSON format using GET method
//
var xhr = new XMLHttpRequest();
var url = "url?data=" + encodeURIComponent(JSON.stringify({"email": "hey@mail.com", "password": "101010"}));
xhr.open("GET", url, true);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
var json = JSON.parse(xhr.responseText);
console.log(json.email + ", " + json.password);
}
};
xhr.send();
使用PHP在服务器端处理JSON格式的数据
// Handling data in JSON format on the server-side using PHP
//
header("Content-Type: application/json");
// build a PHP variable from JSON sent using POST method
$v = json_decode(stripslashes(file_get_contents("php://input")));
// build a PHP variable from JSON sent using GET method
$v = json_decode(stripslashes($_GET["data"]));
// encode the PHP variable to JSON and send it back on client-side
echo json_encode($v);
?>
HTTP
Get请求的长度限制取决于所使用的服务器和客户端(浏览器),范围从2kB-8kB。如果URI的长度超过服务器的处理能力,则服务器应返回414(请求URI太长)状态。
注意 有人说我可以使用状态名称代替状态值。换句话说,我可以使用xhr.readyState ===
xhr.DONE代替。xhr.readyState === 4问题是Internet Explorer使用不同的状态名称,因此最好使用状态值。
2020-05-01