現在の言語: 日本語 |
プリフライトリクエスト |
ajax |
[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.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 here if it's a preflight request
if ($_SERVER[‘REQUEST_METHOD’] === ‘OPTIONS’) {
http_response_code(200);
exit;
}
// Set response format to JSON
header(‘Content-Type: application/json’);
// Get 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.’]);
}
| 著作権情報 |
| ホームページおよプリ等に掲載されている情報等については、いかなる保障もいたしません。 ホームページおよびアプリ等を通じて入手したいかなる情報も複製、販売、出版または使用させたり、 または公開したりすることはできません。 当方は、ホームページおよびアプリ等を利用したいかなる理由によっての障害等が発生しても、 その結果ホームページおよびアプリ等を利用された本人または他の第三者が被った損害について 一切の責任を負わないものとします。 |