javascript - 将 JSON 发送到服务器并返回 JSON,无需 JQuery

我需要向服务器发送一个 JSON(我可以对其进行字符串化)并在用户端检索生成的 JSON,而不使用 JQuery。

如果我应该使用 GET,我如何将 JSON 作为参数传递?会不会有太长的风险?

如果我应该使用 POST,如何在 GET 中设置等效的 onload 函数?

或者我应该使用其他方法吗?

备注

这个问题不是关于发送一个简单的 AJAX。它不应该作为重复关闭。

最佳答案

使用 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 格式的数据

<?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 使用不同的状态名称,所以它是更好地使用状态值。

https://stackoverflow.com/questions/24468459/

相关文章:

json - AngularJS:工厂 $http.get JSON 文件

json - 如何使用 jq 从 JSON 中获取键名

jquery - 为什么找不到我的 json 文件?

javascript - 未捕获的类型错误 : Cannot use 'in' operator t

python - 如何在单元测试中使用 JSON 发送请求

json - 在 VS Code 中,禁用错误 "Comments are not permitte

sql - 查询 JSON 类型内的数组元素

python - 如何在 Python 中美化 JSON?

c# - 解析值时遇到意外字符

json - json.js 和 json2.js 的区别