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

标签 javascript json post get xmlhttprequest

我需要向服务器发送一个 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 使用不同的状态名称,所以它是更好地使用状态值。

关于javascript - 将 JSON 发送到服务器并返回 JSON,无需 JQuery,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24468459/

相关文章:

javascript - Node.js 和 ExpressJS body-parser 包检索数据

php - 回显带有链接 php 的行

javascript - 错误验证 W3C HTML5 img noscript facebook.com

javascript - NetSuite:从 SuiteScript 2.0 中的销售订单获取发货城市

java - 使用 Jackson 将 json 数组转换为数组中具有不同对象元素的 java 对象

javascript - 添加到现有 JSON "Key"的值

php - $_POST 返回 "Undefined index"

javascript - 单击按钮后尝试删除输入并了解为什么在控制台中数组未更新

javascript - 我可以对 HTML 表格的单元格使用 onchange 属性吗?

json - 为什么JSON::XS无法生成有效的UTF-8?