現在の言語: 日本語 |
プリフライトリクエスト |
ajax |
[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' => '指定されたユーザーが見つかりません。']);
}
[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.’]);
}
| 著作権情報 |
| ホームページおよプリ等に掲載されている情報等については、いかなる保障もいたしません。 ホームページおよびアプリ等を通じて入手したいかなる情報も複製、販売、出版または使用させたり、 または公開したりすることはできません。 当方は、ホームページおよびアプリ等を利用したいかなる理由によっての障害等が発生しても、 その結果ホームページおよびアプリ等を利用された本人または他の第三者が被った損害について 一切の責任を負わないものとします。 |