現在の言語: 日本語

戻る

単純リクエスト
ajax

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

[サンプル]

copy
[test1.html(javascript)]
//PHPファイルと連携するURLを指定します
const API_URL = 'http://localhost/test1.php'; 

async function fetchData() {
	try {
		const response = await fetch(API_URL);

		// レスポンスヘッダーに "Access-Control-Allow-Origin" が含まれていなければ、
		// ここでブラウザがエラーを発生させます。
		if (!response.ok) {
			throw new Error('ネットワーク応答が不正です');
		}

		const data = await response.json();
		document.getElementById('output').textContent = 
			'[成功] 結果:\n' + JSON.stringify(data, null, 2);

	} catch (error) {
		// CORSエラーが発生するとここに到達します
		console.error('フェッチ操作で問題が発生しました:', error);
		document.getElementById('output').textContent = 
			'エラーが発生しました。' +
			'\n(PHP側の "Access-Control-Allow-Origin" の設定を確認してください)';
	}
}
[test1.php]
// -----------------------------------------------------
// 1. CORSヘッダーの設定 (最も重要)
// -----------------------------------------------------

//アクセスを許可するオリジンを指定します。
//このサンプルでは、全てのオリジンからのアクセスを許可しています。
header("Access-Control-Allow-Origin: *");

//レスポンスのタイプがJSONであることをブラウザとJSに伝えます
header("Content-Type: application/json; charset=UTF-8");


//-----------------------------------------------------
//2. 実際のリクエスト処理
//-----------------------------------------------------

//返すデータを設定します
$data = array(
	"message" => "Hello test1.html",
	"user_id" => 1234567890,
	"source" => "test data"
);

//データをJSON形式に変換して出力します
echo json_encode($data);
copy
[test1.html(javascript)]
// Specify the URL to interact with the PHP file
const API_URL = ‘http://localhost/test1.php’;

async function fetchData() {
    try {
        const response = await fetch(API_URL);

		// If the response header does not contain “Access-Control-Allow-Origin”,
        // the browser will throw an error here.
        if (!response.ok) {
            throw new Error(‘Invalid network response’);
        }

		const data = await response.json();
        document.getElementById(‘output’).textContent = 
            ‘[Success] Result:\n’ + JSON.stringify(data, null, 2);

    } catch (error) {
        // Reaches here if a CORS error occurs
        console.error(‘Problem occurred during fetch operation:’, error);
		document.getElementById(‘output’).textContent = 
            ‘An error occurred.’ +
            ‘\n(Please check the “Access-Control-Allow-Origin” setting on the PHP side).’;
    }
}
[test1.php]
// --------------------------- --------------------------
// 1. CORS header configuration (most important)
// -----------------------------------------------------

// Specifies origins allowed to access.
// This sample allows access from all origins.
header(“Access-Control-Allow-Origin: *”);

// Informs the browser and JS that the response type is JSON
header(“Content-Type: application/json; charset=UTF-8”);


//------ -----------------------------------------------
//2. Actual Request Handling
//----------------------------------------- ------------

// Set the data to return
$data = array(
    “message” => “Hello test1.html”,
    “user_id” => 1234567890,
    “source” => “test data”
);

// Convert the data to JSON format and output it
echo json_encode($data);

const API_URL = 'http://localhost/test1.php';
PHPファイルと連携するURLを指定します

const response = await fetch(API_URL);
PHPファイル (api.php) にデータ取得のAjaxリクエスト(GETメソッド)を送信します。

if (!response.ok) {
throw new Error('ネットワーク応答が不正です');
}
レスポンスヘッダーに "Access-Control-Allow-Origin" が含まれていなければ、
ここでブラウザがエラーを発生させます。
const data = await response.json();
phpから結果を受け取ります。

document.getElementById('output').textContent =
'[成功] 結果:\n' + JSON.stringify(data, null, 2);
結果を表示します。

} catch (error) {
失敗した場合の処理を実装します。




戻る

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