Wysyłanie JSON na serwer i odzyskiwanie JSON w zamian, bez JQuery

Muszę wysłać JSON (który mogę stringify) do serwera i pobrać wynikowy JSON Po Stronie Użytkownika, bez użycia JQuery.

Jeśli powinienem użyć GET, jak przekazać JSON jako parametr? Czy istnieje ryzyko, że będzie to zbyt długie?

Jeśli powinienem użyć posta, jak ustawić odpowiednik onload funkcji w GET?

Czy powinienem użyć innej metody?

Uwaga

To pytanie nie dotyczy wysyłania prostego AJAX ' a. Nie powinno być zamknięte jako DUPLIKAT.

Author: Damjan Pavlica, 2014-06-28

1 answers

Wysyłanie i odbieranie danych w formacie JSON metodą POST

// 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);

Wysyłanie danych w formacie JSON przy użyciu metody GET

// 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();

Obsługa danych w formacie JSON po stronie serwera przy użyciu PHP

<?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);
?>

Limit długości żądania HTTP Get jest zależny zarówno od serwera, jak i klienta (przeglądarki), z 2kB - 8kB. Serwer powinien zwrócić status 414 (Request-URI Too Long), jeśli URI jest dłuższy niż serwer może uchwyt.

Uwaga ktoś powiedział, że mogę używać nazw Stanów zamiast wartości stanu; innymi słowy mogę używać xhr.readyState === xhr.DONE zamiast xhr.readyState === 4 Problem polega na tym, że Internet Explorer używa różnych nazw stanów, więc lepiej jest używać wartości stanu.

 138
Author: hex494D49,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-04-03 11:04:40