現在の言語: 日本語

戻る

get
ajax

ajaxを使用してhtml側からサーバーにリクエストします。
サーバーではphpを使用して判定した結果をhtml側で受け取ります。
このサンプルではgetを使用したデータ表示の例となります。

[サンプル]

copy
[test5.html(javascript)]
sendData();
function sendData() {
	const tmp = "sample test data";
	const result = document.getElementById('result');

	// GETリクエストのURLを構築
	// クエリパラメータとして名前を付与
	const url = "./img/test5.php?data=${encodeURIComponent(tmp)}";

	// Fetch APIを使用してGETリクエストを送信
	fetch(url)
		.then(response => {
			// サーバーからの応答をJSONとして解析
			if (!response.ok) {
				throw new Error('ネットワーク応答が不正です。');
			}
			return response.json();
		})
		.then(data => {
			// PHPから受け取ったメッセージを表示
			result.textContent = data.message;
		})
		.catch(error => {
			// エラー発生時の処理
			console.error('フェッチ操作に問題がありました:', error);
			result.textContent = '通信エラーが発生しました。';
		});
}

[test5.php]
// クロスオリジンリソース共有 (CORS) 設定
// 開発環境では全てのオリジンからのアクセスを許可するが、
// 本番環境では特定のオリジンのみ許可するように変更することを推奨
header('Access-Control-Allow-Origin: GET');

// 返却するデータの形式がJSONであることを指定
header('Content-Type: application/json; charset=UTF-8');

// GETリクエストから 'user_name' パラメータを取得
// $_GETはGETパラメータを格納するPHPのスーパーグローバル変数
if (isset($_GET['data'])) {
    $data = htmlspecialchars($_GET['data']); // クロスサイトスクリプティング (XSS) 対策
    $message = "php側で受け取ったデータ(" . $data . ")";
} else {
    $message = "データが指定されていません。";
}

// レスポンスデータを連想配列として準備
$response = [
    'status' => 'success',
    'message' => $message
];

// 連想配列をJSON形式に変換して出力
echo json_encode($response);
copy
[test5.html(javascript)]
sendData();
function sendData() {
    const tmp = “sample test data”;
    const result = document.getElementById(‘result’);

    // Construct the GET request URL
    // Append the name as a query parameter
	const url = "./img/test5.php?data=${encodeURIComponent(tmp)}";

    // Send GET request using Fetch API
    fetch(url)
        .then(response => {
            // Parse server response as JSON
            if (!response.ok) {
				throw new Error(‘Invalid network response.’);
            }
            return response.json();
        })
        .then(data => {
            // Display the message received from PHP
            result.textContent = data.message;
        })
        .catch(error => {
            // Handle error occurrence
			console.error(‘Problem with fetch operation:’, error);
            result.textContent = ‘A communication error occurred.’;
        });
}

[test5.php]
// Cross-Origin Resource Sharing (CORS) configuration
// In development environments, allow access from all origins,
// but it is recommended to change this to allow only specific origins in production environments
header(‘Access-Control-Allow-Origin: GET’);

// Specify that the returned data format is JSON
header(‘Content-Type: application/json; charset=UTF-8’);

// Retrieve the ‘user_name’ parameter from the GET request
// $_GET is PHP's superglobal variable storing GET parameters
if (isset($_GET[‘data’])) {
    $data = htmlspecialchars($_GET[‘data’]); // Cross-site scripting (XSS) prevention
    $message = “Data received on the PHP side: (” . $data . “)”;
} else {
    $message = “No data specified.”;
}

// Prepare response data as an associative array
$response = [
    ‘status’ => ‘success’,
    ‘message’ => $message
];

// Convert associative array to JSON format and output
echo json_encode($response);

$_GET変数を使った基本的な非同期通信の仕組みを示しています。JavaScriptが裏側でPHPスクリプト(test5.php?data=...)にリクエストを送信しますが、
現在表示されているHTMLページ(test5.html)はそのままの状態を維持します。
ブラウザのアドレスバーは変化しません。

GETリクエストのデータ(URLとクエリパラメータ)のサイズ
※ブラウザとウェブサーバによって制限されます。

目安一般的に2,000文字〜8,000文字(約2KB〜8KB)程度が安全な範囲とされています。
理由URLの長さには物理的な制限があり、これを超えるとリクエスト自体が失敗します。
画像送信GETで画像データ(Base64エンコードされたものを含む)を送信することは、
データ量がこの制限を容易に超えてしまうため、非推奨です。

const url = "./img/test5.php?data=${encodeURIComponent(tmp)}";
クエリパラメータを準備します。
今回はdataというGETパラメータの値にencodeURIComponent(tmp)を指定しています。
tmp変数に設定したように「sample test data」という値です。
fetch(url)
fetchのコード部分がバックグラウンドでの通信を可能にしています。
Fetch APIを使用してGETリクエストを送信します。
送信先のphpのパスは「./img/test5.php」です。

return response.json();
データ本体を読み込む指示を出します。
result.textContent = data.message;
phpから受け取ったデータを表示します。
エンドユーザーがアドレスバーを見ただけでは、
どのようなデータがやり取りされているかを直接知ることはできません。
ただし、ブラウザの開発者ツールの「Network」タブを使用すると、通信履歴を容易に確認できます。




戻る

著作権情報
ホームページおよプリ等に掲載されている情報等については、いかなる保障もいたしません。
ホームページおよびアプリ等を通じて入手したいかなる情報も複製、販売、出版または使用させたり、
または公開したりすることはできません。
当方は、ホームページおよびアプリ等を利用したいかなる理由によっての障害等が発生しても、
その結果ホームページおよびアプリ等を利用された本人または他の第三者が被った損害について
一切の責任を負わないものとします。