現在の言語: 日本語

戻る

プリフライトリクエスト
ajax

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

[サンプル]

copy
[test2.html(javascript)]
document.getElementById('fetchButton').addEventListener('click', () => {
	const resultDiv = document.getElementById('result');
	resultDiv.textContent = '読み込み中...';

	fetch('http://localhost/test2.php', {
		method: 'POST',
		headers: {
		'Content-Type': 'application/json',
		},
		body: JSON.stringify({ id: 123 }),
	})
	.then(response => {
		if (!response.ok) {
			throw new Error('ネットワークエラーが発生しました');
		}
		return response.json();
	})
	.then(data => {
		if (data.status === 'success') 
		{
			resultDiv.innerHTML = `
				<p>名前: ${data.user.name}</p>
				<p>年齢: ${data.user.age}</p>
			`;
		} 
		else 
		{
			resultDiv.textContent = `エラー: ${data.message}`;
		}
	})
	.catch(error => {
		console.error('Fetchエラー:', error);
		resultDiv.textContent = `リクエストに失敗しました: ${error.message}`;
	});
});
[test2.php]
//CORSを許可する
header("Access-Control-Allow-Origin: *"); // すべてのオリジンを許可(セキュリティ的に注意)
header("Access-Control-Allow-Methods: POST, GET, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type");
 
// プリフライトリクエストならここで終了
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
	http_response_code(200);
	exit;
}
 
// レスポンスの形式をJSONに設定
header('Content-Type: application/json');
 
// POSTされたJSONデータを取得
$json_data = file_get_contents("php://input");
$data = json_decode($json_data, true);
 
// データを検証
if (!isset($data['id'])) 
{
	echo json_encode(['status' => 'error', 'message' => 'ユーザーIDが指定されていません。']);
	exit;
}
 
$id = $data['id'];
 
// ダミーのデータ処理
if ($id === 123) 
{
	$user = [
		'name' => '山田 花子',
		'age' => 20
	];
	echo json_encode(['status' => 'success', 'user' => $user]);
} 
else 
{
	echo json_encode(['status' => 'error', 'message' => '指定されたユーザーが見つかりません。']);
}
copy
[test2.html(javascript)]
document.getElementById(‘fetchButton’).addEventListener(‘click’, () => {
    const resultDiv = document.getElementById(‘result’);
    resultDiv.textContent = ‘Loading...’;

	fetch(‘http://localhost/test2.php’, {
    method: ‘POST’,
    headers: {
        ‘Content-Type’: ‘application/json’,
    },
    body: JSON.stringify({ id: 123 }),
})
	.then(response => {
    if (!response.ok) {
        throw new Error(‘Network error occurred’);
    }
    return response.json();
})
.then(data => {
    if (data.status === ‘success’) {
        resultDiv.innerHTML = `
				<p>Name: ${data.user.name}</p>
				<p>Age: ${data.user.age}</p>
            `;
        } 
        else 
        {
            resultDiv.textContent = `Error: ${data.message}`;
        }
    })
	.catch(error => {
        console.error(‘Fetch error:’, error);
        resultDiv.textContent = `Request failed: ${error.message}`;
    });
});
[test2.php]
// Allow CORS
header(“Access-Control-Allow-Origin: *”); // Allow all origins (security caution)
header(“Access-Control-Allow-Methods: POST, GET, OPTIONS”);
header(“Access-Control-Allow-Headers: Content-Type”);
 
// Exit if this is a preflight request
if ($_SERVER[‘REQUEST_METHOD’] === ‘OPTIONS’) {
    http_response_code(200);
    exit;
}
 
// Set response format to JSON
header(‘Content-Type: application/json’);
 
// Retrieve the POSTed JSON data
$json_data = file_get_contents(“php://input”);
$data = json_decode($json_data, true);
 
// Validate the data
if (!isset($data[‘id’])) 
{
    echo json_encode([‘status’ => ‘error’, ‘message’ => ‘User ID is not specified.’]);
	exit;
}
 
$id = $data[‘id’];
 
// Dummy data processing
if ($id === 123) 
{
    $user = [
        ‘name’ => ‘Hanako Yamada’,
        ‘age’ => 20
    ];
	echo json_encode([‘status’ => ‘success’, ‘user’ => $user]);
} 
else 
{
    echo json_encode([‘status’ => ‘error’, ‘message’ => ‘The specified user was not found.’]);
}

fetch('http://localhost/test2.php'
PHPファイルと連携するURLを指定します

method: 'POST',
POST形式を指定しています。

headers: {
'Content-Type': 'application/json',
送信するデータの形式を指定します。

body: JSON.stringify({ id: 123 }),
JSON.stringify:JavaScriptオブジェクトをJSON文字列に変換します。
{ id: 123 }
オブジェクト・リテラルという方法で作成された「オブジェクト」です。
プロパティ(フィールド)と値の組み合わせのデータを送信しています。

.then(response => {
response オブジェクトを受け取ります。

return response.json();
データ本体を読み込む指示を出します。

.then(data => {if (data.status === 'success')
非同期で実行されます。
response.json() が完了したときに
引数のdata(実際に読み込まれたJSONデータ)を受け取ることができます。



戻る

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