JQueryを使用せずにJSONをサーバーに送信し、JSONを取得する質問する

JQueryを使用せずにJSONをサーバーに送信し、JSONを取得する質問する

JQuery を使用せずに、JSON (文字列化できる) をサーバーに送信し、結果の JSON をユーザー側で取得する必要があります。

GET を使用する場合、JSON をパラメータとして渡すにはどうすればよいですか? 長くなりすぎるリスクはありますか?

POST を使用する場合、onloadGET の関数と同等のものをどのように設定すればよいでしょうか?

それとも別の方法を使うべきでしょうか?

述べる

この質問は単純な AJAX の送信に関するものではありません。重複として閉じるべきではありません。

ベストアンサー1

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) ステータスを返す必要があります。

注記状態値の代わりに状態名を使用できると誰かが言っていました。つまり、xhr.readyState === xhr.DONEの代わりにを使用できるxhr.readyState === 4ということです。問題は、Internet Explorer が異なる状態名を使用するため、状態値を使用する方がよいということです。

おすすめ記事