現在の言語: 日本語

戻る

画像とテキストを表示
ajax

ajaxを使用したストーリを表示するサンプルです。
ボタンを選択することでストーリー管理番号をjavascriptからphpに渡します。
受け取った管理番号と言語管理番号を判定して
ストーリーの画像とテキストをphp側で準備したデータを返します。

[サンプル]

copy
[test10.php]
// ホスト名が特定の文字列で終わっているかチェックする
$host = $_SERVER['HTTP_HOST'];
$checkURL = "localhost";

if (substr($host, -strlen($checkURL)) !== $checkURL) 
{
    header("HTTP/1.1 403 Forbidden");
    exit("Forbidden");
}

// --- CORS 設定 ---
header("Access-Control-Allow-Origin: http://localhost");
header("Access-Control-Allow-Credentials: true");

//pageIndexはjsから受け取るように実装すること
// POSTされたJSONデータを取得
$json_data = file_get_contents("php://input");
$data = json_decode($json_data, true); // trueを指定すると連想配列としてデコードされる
 
// 受信したデータを検証(例)
if (!isset($data['no']) || !isset($data['lang'])) {
    echo json_encode(['status' => 'error', 'message' => 'データが不足しているか、形式が不正です。']);
    exit;
}

// 画像ファイルのパス
// 受信した配列データにアクセス
$pageIndex = $data['no'];
$lang = $data['lang'];
// 画像ファイル名を取得
$story="";
$story = storyText($lang, $pageIndex);

// JSONとして返す
header("Content-Type: application/json");
echo json_encode([
    'status' => 'success',
    'story' => $story
]);
exit;
//表示するストーリーテキスト
function storyText(int $lang,int $pageIndex):string
{
    $story="";
    $storyEn="";
    switch($pageIndex)
    {
        case 0:
            $story = "こんにちは";
            $storyEn = "Hello";
            break;
        case 1:
            $story = "おや、どうしたんだい?";
            $storyEn = "Hey, what's wrong?";
            break;
        case 2:
            $story = "お腹へっちゃって";
            $storyEn = "I'm hungry";
            break;
        case 3:
            $story = "野菜はどう?";
            $storyEn = "What about vegetables?";
            break;
        case 4:
            $story = "それは、ちょっと";
            $storyEn = "That's a bit";
            break;
        case 5:
            $story = "あぁ、そういえばこれ拾ったんだった。\n(どんぐりを差し出す)";
            $storyEn = "Ah, that reminds me, I picked this up. \n (Hands over the acorn)";
            break;
        case 6:
            $story = "いいの?\nありがとう";
            $storyEn = "Is that okay?\nThank you";
            break;
        case 7:
            $story = "どういたしまして\n(こうしてくまさんは森へ帰っていきました。)";
            $storyEn = "You're welcome.\n(And so the bear returned to the forest.)";
            break;
    }
    return $lang==0?$story : $storyEn;
}

[getImage.php]
// CORS設定
header("Access-Control-Allow-Origin: http://localhost");
header("Access-Control-Allow-Credentials: true");

// POSTされたJSONデータを取得
$json_data = file_get_contents("php://input");
$data = json_decode($json_data, true);

// チェック
if (!isset($data['no'])) {
    header("HTTP/1.1 400 Bad Request");
    exit("Missing parameter");
}

$pageIndex = $data['no'];
$file = fileID($pageIndex);
$path = __DIR__ . "/" . $file;

if (!file_exists($path)) {
    header("HTTP/1.1 404 Not Found");
    exit("Image not found");
}

// MIMEタイプを取得して画像を返す
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mime  = finfo_file($finfo, $path);
finfo_close($finfo);

header("Content-Type: $mime");
readfile($path);
exit;

function fileID(int $pageIndex): string {
    switch($pageIndex) {
        case 0: return "nawmin_sample2.png";
        case 1: return "nawmin_sample4.png";
        case 2: return "nawmin_sample2.png";
        case 3: return "nawmin_sample5.png";
        case 4: return "nawmin_sample2.png";
        case 5: return "nawmin_sample3.png";
        case 6: return "nawmin_sample2.png";
        case 7: return "nawmin_sample4.png";
        default: return "nawmin_sample2.png";
    }
}

[test10.php]
// Check if the host name ends with a specific string
$host = $_SERVER['HTTP_HOST'];
$checkURL = "localhost";

if (substr($host, -strlen($checkURL)) !== $checkURL) 
{
    header("HTTP/1.1 403 Forbidden");
    exit("Forbidden");
}

// --- CORS settings ---
header("Access-Control-Allow-Origin: http://localhost");
header("Access-Control-Allow-Credentials: true");

// Implement so that pageIndex is received from js
// Get the POSTed JSON data
$json_data = file_get_contents("php://input");
$data = json_decode($json_data, true); // Specify true to decode as an associative array
 
// Validate the received data (example)
if (!isset($data['no']) || !isset($data['lang'])) {
    echo json_encode(['status' => 'error', 'message' => 'Data is missing or the format is invalid.']);
    exit;
}

// Path to the image file
// Access the received array data
$pageIndex = $data['no'];
$lang = $data['lang'];
// Get the image file name
$story="";
$story = storyText($lang, $pageIndex);

// Return as JSON
header("Content-Type: application/json");
echo json_encode([
    'status' => 'success',
    'story' => $story
]);
exit;
// Story text to be displayed
function storyText(int $lang,int $pageIndex):string
{
    $story="";
    $storyEn="";
    switch($pageIndex)
    {
        case 0:
            $story = "こんにちは";
            $storyEn = "Hello";
            break;
        case 1:
            $story = "おや、どうしたんだい?";
            $storyEn = "Hey, what's wrong?";
            break;
        case 2:
            $story = "お腹へっちゃって";
            $storyEn = "I'm hungry";
            break;
        case 3:
            $story = "野菜はどう?";
            $storyEn = "What about vegetables?";
            break;
        case 4:
            $story = "それは、ちょっと";
            $storyEn = "That's a bit";
            break;
        case 5:
            $story = "あぁ、そういえばこれ拾ったんだった。\n(どんぐりを差し出す)";
            $storyEn = "Ah, that reminds me, I picked this up. \n (Hands over the acorn)";
            break;
        case 6:
            $story = "いいの?\nありがとう";
            $storyEn = "Is that okay?\nThank you";
            break;
        case 7:
            $story = "どういたしまして\n(こうしてくまさんは森へ帰っていきました。)";
            $storyEn = "You're welcome.\n(And so the bear returned to the forest.)";
            break;
    }
    return $lang==0?$story : $storyEn;
}

[getImage.php]
// CORS settings
header("Access-Control-Allow-Origin: http://localhost");
header("Access-Control-Allow-Credentials: true");

// Get the POSTed JSON data
$json_data = file_get_contents("php://input");
$data = json_decode($json_data, true);

// Check
if (!isset($data['no'])) {
    header("HTTP/1.1 400 Bad Request");
    exit("Missing parameter");
}

$pageIndex = $data['no'];
$file = fileID($pageIndex);
$path = __DIR__ . "/" . $file;

if (!file_exists($path)) {
    header("HTTP/1.1 404 Not Found");
    exit("Image not found");
}

// Get MIME type and return the image
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mime  = finfo_file($finfo, $path);
finfo_close($finfo);

header("Content-Type: $mime");
readfile($path);
exit;

function fileID(int $pageIndex): string {
    switch($pageIndex) {
        case 0: return "nawmin_sample2.png";
        case 1: return "nawmin_sample4.png";
        case 2: return "nawmin_sample2.png";
        case 3: return "nawmin_sample5.png";
        case 4: return "nawmin_sample2.png";
        case 5: return "nawmin_sample3.png";
        case 6: return "nawmin_sample2.png";
        case 7: return "nawmin_sample4.png";
        default: return "nawmin_sample2.png";
    }
}
copy

HTTPレスポンスは「1つの形式」しか返せないため2つに分けて
画像とストーリーのテキストを実行しています。
例えば、phpで
readfile($path)と実行して画像ファイルのバイナリデータを出力しようとします。
そのあとに echo json_encode(...) でJSONテキストを出力しようとしても
ブラウザは最初のバイナリを「画像」として処理しようとするため
JSONは無視されるか、壊れたデータとなります。
これを防ぐためにも画像を表示するphpとストーリーを表示するphpに分けて処理をしています。

$pageIndex = $data['no'];
$lang = $data['lang'];
html側のjavascript
body: JSON.stringify({ no: no, lang: 0 }),
を実行することで受け取ったデータを各変数に設定しています。

function storyText(int $lang,int $pageIndex):string
このサンプルでは
lang:言語
pageIndex:0から始まるページ管理番号
1ページは1-1=0というように1を減算した番号で管理したものを判定しています。

return $lang==0?$story : $storyEn;
三項演算子を使ってストーリーテキストを日本語および英語に判定した結果の変数を返しています。

header("Content-Type: application/json");
echo json_encode([
'status' => 'success',
'story' => $story
]);
html側に返す処理として取得したデータを返しています。
json_encodeで設定したストーリーテキスト変数($story)を
連想配列'story' => $storyとすることで
html側のjavascriptでdata.storyのように取得して使用できるようにしています。

$json_data = file_get_contents("php://input");
$data = json_decode($json_data, true);
POSTされたJSONデータを取得します。

$file = fileID($pageIndex);
$path = __DIR__ . "/" . $file;
fileID関数の引数のページ管理番号から判定して
表示したい画像のパスを変数に保存します。

$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mime = finfo_file($finfo, $path);
finfo_close($finfo);
finfo_file関数でMIMEタイプを取得しています。

header("Content-Type: $mime");
$mine変数で指定された種類の(img/post.png)ということを伝えます。
ブラウザが受け取ったデータを画像として解釈する準備をできることになります。

readfile($path);
画像ファイルの中身をそバイナリ出力します。




戻る

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