現在の言語: 日本語

戻る

画像とテキストを表示
ajax

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

[サンプル]

copy
[test7.html(javascript)]
const b1 = document.getElementById("btn1");
const b2 = document.getElementById("btn2");
let pageIndex=0;
let pageMax=8;
displayScreen();
buttonDisplay(pageIndex);
//戻る
b1.addEventListener("click", () => 
{
	//画像を表示する
	//ストーリーを表示する
	//ボタンの表示有無
	pageIndex--;
	if(pageIndex < 0) pageIndex = 0;
	displayScreen();
	buttonDisplay(pageIndex);
});
//進む
b2.addEventListener("click", () => 
{
	pageIndex++;
	if(pageIndex >= pageMax)pageIndex = pageMax - 1;
	displayScreen();
	buttonDisplay();
});
function buttonDisplay()
{
	b1.style.visibility="visible";
	b2.style.visibility="visible";
	if(pageIndex==0)
	{
		b1.style.visibility="hidden";
	}
	if(pageIndex + 1 == pageMax)
	{
		b2.style.visibility="hidden";
	}
}
async function displayScreen() {
    let no = pageIndex;

    // ストーリー取得
    fetch("http://localhost/img/test10.php", {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ no: no, lang: 0 }),
    })
    .then(res => res.json())
    .then(data => {
        document.getElementById("story").innerText = data.story;
    });

    // 画像取得(Blobとして)
    fetch("http://localhost/img/getImage.php", {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ no: no }),
    })
    .then(res => res.blob())
    .then(blob => {
        const url = URL.createObjectURL(blob);
        document.getElementById("img").src = url;
    })
    .catch(err => console.error("画像取得失敗:", err));
}
displayImage("./img/back","img_back");
displayImage("./img/forward","img_forward");
function displayImage(d1,d2)
{
	fetch(d1)
	.then(response=>response.text())/*テキストデータとして取得*/
	.then(d=>{
		/*取得したBase64データを`img`の`src`に設定*/
		const i1=document.getElementById(d2);
		i1.src=d;
		/*画像の読み込みが完了したらコンソールにログを表示*/
		i1.onload=function(){
			/*console.log("画像の読み込みが完了しました");*/
		};
	})
	.catch(error=>{
		/*console.error("画像の取得に失敗しました",error);*/
	});
}
copy
const b1 = document.getElementById("btn1");
const b2 = document.getElementById("btn2");
let pageIndex=0;
let pageMax=8;
displayScreen();
buttonDisplay(pageIndex);
// Back
b1.addEventListener("click", () => 
{
    // Display the image
    // Display the story
    // Show/hide buttons
    pageIndex--;
    if(pageIndex < 0) pageIndex = 0;
    displayScreen();
    buttonDisplay(pageIndex);
});
// Forward
b2.addEventListener("click", () => 
{
    pageIndex++;
    if(pageIndex >= pageMax)pageIndex = pageMax - 1;
    displayScreen();
    buttonDisplay();
});
function buttonDisplay()
{
    b1.style.visibility="visible";
    b2.style.visibility="visible";
    if(pageIndex==0)
    {
        b1.style.visibility="hidden";
    }
    if(pageIndex + 1 == pageMax)
    {
        b2.style.visibility="hidden";
    }
}
async function displayScreen() {
    let no = pageIndex;

    // Get story
    fetch("http://localhost/img/test10.php", {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ no: no, lang: 0 }),
    })
    .then(res => res.json())
    .then(data => {
        document.getElementById("story").innerText = data.story;
    });

    // Get image (as Blob)
    fetch("http://localhost/img/getImage.php", {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ no: no }),
    })
    .then(res => res.blob())
    .then(blob => {
        const url = URL.createObjectURL(blob);
        document.getElementById("img").src = url;
    })
    .catch(err => console.error("Image acquisition failed:", err));
}
displayImage("./img/back","img_back");
displayImage("./img/forward","img_forward");
function displayImage(d1,d2)
{
    fetch(d1)
    .then(response=>response.text())/* Retrieve as text data */
    .then(d=>{
        /* Set the retrieved Base64 data to `img`'s `src` */
        const i1=document.getElementById(d2);
        i1.src=d;
        /* When image loading is complete, display log in console */
        i1.onload=function(){
            /*console.log("Image loading completed");*/
        };
    })
    .catch(error=>{
        /*console.error("Failed to retrieve image",error);*/
    });
}

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

function buttonDisplay()
if(pageIndex==0)
ページの開始のケース
btn1(戻るボタン)を非表示にしています。
if(pageIndex + 1 == pageMax)
ページの最後のケース
btn2(進むボタン)を非表示にしています。

displayScreen()はjavascriptからphpに送信をして結果を受け取る関数です。

fetch("http://localhost/img/test10.php", {
ストーリーを受け取るためのフェッチをしています。
body: JSON.stringify({ no: no, lang: 0 }),
ここでは固定でlang([0]jp [1]en)を設定していますが、必要に応じて変更してください。

document.getElementById("story").innerText = data.story;
phpで準備したデータを受け取りdivタグ内に表示しています。

fetch("http://localhost/img/getImage.php", {
画像を取得するphpにフェッチしています。

body: JSON.stringify({ no: no }),
画像管理番号がわかればいいだけなのでnoのみを渡しています。

const url = URL.createObjectURL(blob);
バイナリデータとして受け取ったデータをBlobを画像として表示できるURLに変換しています。

document.getElementById("img").src = url;
受け取ったデータをsrcプロパティに設定して画像を表示しています。




戻る

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