我需要向服务器发送一个 JSON(我可以将其字符串化)并在用户端检索生成的 JSON,而不使用 JQuery。
如果我应该使用 GET,我如何将 JSON 作为参数传递?时间长了会有风险吗?
如果我应该使用 POST,我如何onload在 GET 中设置等效的函数?
或者我应该使用不同的方法?
评论
这个问题不是关于发送一个简单的 AJAX。它不应作为重复关闭。
我需要向服务器发送一个 JSON(我可以将其字符串化)并在用户端检索生成的 JSON,而不使用 JQuery。
如果我应该使用 GET,我如何将 JSON 作为参数传递?时间长了会有风险吗?
如果我应该使用 POST,我如何onload在 GET 中设置等效的函数?
或者我应该使用不同的方法?
评论
这个问题不是关于发送一个简单的 AJAX。它不应作为重复关闭。
// 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);
// 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
// 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(Request-URI Too Long)状态。
注意有人说我可以使用状态名称而不是状态值;换句话说,我可以使用xhr.readyState === xhr.DONE而不是xhr.readyState === 4问题是 Internet Explorer 使用不同的状态名称,因此最好使用状态值。
使用新的 api fetch:
const dataToSend = JSON.stringify({"email": "hey@mail.com", "password": "101010"});
let dataReceived = "";
fetch("", {
credentials: "same-origin",
mode: "same-origin",
method: "post",
headers: { "Content-Type": "application/json" },
body: dataToSend
})
.then(resp => {
if (resp.status === 200) {
return resp.json()
} else {
console.log("Status: " + resp.status)
return Promise.reject("server")
}
})
.then(dataJson => {
dataReceived = JSON.parse(dataJson)
})
.catch(err => {
if (err === "server") return
console.log(err)
})
console.log(`Received: ${dataReceived}`)