问题描述
我需要向服务器发送一个 JSON(我可以对其进行字符串化)并在用户端检索生成的 JSON,而不使用 JQuery.
I need to send a JSON (which I can stringify) to the server and to retrieve the resulting JSON on the user side, without using JQuery.
如果我应该使用 GET,我如何将 JSON 作为参数传递?会不会有太长的风险?
If I should use a GET, how do I pass the JSON as a parameter? Is there a risk it would be too long?
如果我应该使用 POST,如何在 GET 中设置等效的 onload
函数?
If I should use a POST, how do I set the equivalent of an onload
function in GET?
或者我应该使用其他方法吗?
Or should I use a different method?
备注
这个问题不是关于发送一个简单的 AJAX.它不应该作为重复关闭.
This question is not about sending a simple AJAX. It should not be closed as duplicate.
推荐答案
使用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": "[email protected]", "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": "[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 在服务器端处理 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)状态.
The limit of the length of an HTTP Get request is dependent on both the server and the client (browser) used, from 2kB - 8kB. The server should return 414 (Request-URI Too Long) status if an URI is longer than the server can handle.
注意 有人说我可以用状态名代替状态值;换句话说,我可以使用 xhr.readyState === xhr.DONE
而不是 xhr.readyState === 4
问题是 Internet Explorer 使用不同的状态名称,所以它是更好地使用状态值.
Note Someone said that I could use state names instead of state values; in other words I could use xhr.readyState === xhr.DONE
instead of xhr.readyState === 4
The problem is that Internet Explorer uses different state names so it's better to use state values.
这篇关于将 JSON 发送到服务器并返回 JSON,无需 JQuery的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!