我需要将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": "[email protected]", "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": "[email protected]", "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(请求URI太长)状态。
注意有人说我可以使用状态名称代替状态值。换句话说,我可以使用xhr.readyState === xhr.DONE
而不是使用xhr.readyState === 4
问题是Internet Explorer使用不同的状态名称,因此最好使用状态值。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句