問題描述
我需要向服務器發送一個 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": "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)狀態.
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的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!