現在の言語: 日本語

戻る

ajaxで画像とストーリを自動表示
ajax

ajaxを使用したストーリを表示するサンプルです。
自動的に画像とテキストが切り替わります。

[サンプル]

copy
[test11.html(javascript)]
let pageIndex = 0;
const pageMax = 8;
let timerId = null; //setTimeoutのIDを保持します
let isRunning = false;

async function displayScreen() 
{
	if (!isRunning) return;
	
	console.log("ページインデックス:", pageIndex);
	const imgEl = document.getElementById("img");
	const storyEl = document.getElementById("story");
	
	imgEl.className = "";
	storyEl.className = "";
	
	try {
		const storyRes = await fetch("/img/test11.php", {
			method: "POST",
			headers: { "Content-Type": "application/json" },
			body: JSON.stringify({ no: pageIndex, lang: 0 }),
		});
		const storyData = await storyRes.json();
		console.log("ストーリー取得成功:", storyData.story);
		storyEl.innerText = storyData.story;
		fadeIn(storyEl);
	} catch (e) {
		console.error("ストーリー取得失敗:", e);
	}
	
	try {
		const imgRes = await fetch("/img/getImage2.php", {
			method: "POST",
			headers: { "Content-Type": "application/json" },
			body: JSON.stringify({ no: pageIndex }),
		});
		const blob = await imgRes.blob();
		const url = URL.createObjectURL(blob);
		console.log("画像URL:", url);
		imgEl.onload = () => fadeIn(imgEl);
		imgEl.src = url;
	} catch (e) {
		console.error("画像取得失敗:", e);
	}
	
	// 次のページへ進む前に、終了条件をチェック!
	if (pageIndex >= pageMax - 1) {
		console.log("自動停止します。");
		isRunning = false;
		return; // ここで終了!
	}
	
	pageIndex++;
	timerId = setTimeout(displayScreen, 3000);
}

function fadeIn(element) {
	element.className = "";
	requestAnimationFrame(() => {
		requestAnimationFrame(() => {
			element.classList.add("visible");
			console.log("→ .visible クラス追加:", element.id);
		});
	});
}

// 停止ボタン
document.getElementById("stopBtn").addEventListener("click", () => {
	isRunning = false;
	clearTimeout(timerId);
	console.log("⏹️ 停止しました");
});

// リセットボタン
document.getElementById("resetBtn").addEventListener("click", () => {
	clearTimeout(timerId);
	pageIndex = 0;
	isRunning = true;
	displayScreen();
	console.log("🔄 リセットして再開!");
});

// 最初にスタート
isRunning = true;
displayScreen();
copy
[test11.html(javascript)]
let pageIndex = 0;
const pageMax = 8;
let timerId = null; //Retains the setTimeout ID
let isRunning = false;

async function displayScreen()
{
	if (!isRunning) return;
	
	console.log("Page Index:", pageIndex);
	const imgEl = document.getElementById("img");
	const storyEl = document.getElementById("story");
	
	imgEl.className = "";
	storyEl.className = "";
	
	try {
		const storyRes = await fetch("/img/test11.php", {
			method: "POST",
			headers: { "Content-Type": "application/json" },
			body: JSON.stringify({ no: pageIndex, lang: 0 }),
		});
		const storyData = await storyRes.json();
		console.log("Story successfully retrieved:", storyData.story);
		storyEl.innerText = storyData.story;
		fadeIn(storyEl);
	} catch (e) {
		console.error("Failed to retrieve story:", e);
	}
	
	try {
		const imgRes = await fetch("/img/getImage2.php", {
			method: "POST",
			headers: { "Content-Type": "application/json" },
			body: JSON.stringify({ no: pageIndex }),
		});
		const blob = await imgRes.blob();
		const url = URL.createObjectURL(blob);
		console.log("Image URL:", url);
		imgEl.onload = () => fadeIn(imgEl);
		imgEl.src = url;
	} catch (e) {
		console.error("Failed to retrieve image:", e);
	}
	
	// Check the termination condition before proceeding to the next page!
	if (pageIndex >= pageMax - 1) {
		console.log("Automatically pausing.");
		isRunning = false;
		return; // Stop here!
	}
	
	pageIndex++;
	timerId = setTimeout(displayScreen, 3000);
}

function fadeIn(element) {
	element.className = "";
	requestAnimationFrame(() => {
		requestAnimationFrame(() => {
			element.classList.add("visible");
			console.log("→ .visible class added:", element.id);
		});
	});
}

// Stop button
document.getElementById("stopBtn").addEventListener("click", () => {
	isRunning = false;
	clearTimeout(timerId);
	console.log("⏹️ Stopped");
});

// Reset button
document.getElementById("resetBtn").addEventListener("click", () => {
	clearTimeout(timerId);
	pageIndex = 0;
	isRunning = true;
	displayScreen();
	console.log("🔄 Reset and restart!");
});

// Start at the beginning
isRunning = true;
displayScreen();

displayScreen
画像とテキストを変更する関数です。

timerId = setTimeout(displayScreen, 3000);
次の画像とテキストを読み込んでいる場所です。

const storyRes = await fetch("/img/test11.php", {
テキストを読み込むためのフェッチ処理をします。

body: JSON.stringify({ no: pageIndex, lang: 0 }),
phpで判定するための値を送っています。

const storyData = await storyRes.json();
データ本体を読み込む指示を出します。

storyEl.innerText = storyData.story;
取得したテキストを表示します。

requestAnimationFrame(() => {
requestAnimationFrame(() => {
requestAnimationFrame を2回使い、ブラウザに「class変更→トランジション開始」を確実に認識させます。

const imgRes = await fetch("/img/getImage2.php", {
画像を読み込むためフェッチします。

imgEl.onload = () => fadeIn(imgEl);
imgEl.src = url;
イベントを登録後、srcプロパティに画像を設定します。

#img, #story {
opacity: 0;
transition: opacity 0.5s ease-in-out;
display: block;
}
displayを明示しておきます。

.visible {
opacity: 1 !important;
}
.visible に !important を追加してcssの他のスタイルに上書きされず、確実に表示されるようになります。
const storyRes = await fetch("/img/test11.php", {
constを忘れて storyData = await ... だけだと、スコープ外で使えずエラーになることがあります。

isRunning = false;
clearTimeout(timerId);
停止ボタンの処理
表示のループを止める処理です。
isRunning変数をfalseにすることでdisplayScreen関数の
if (!isRunning) return;
制御でdisplayScreenの処理を実行しないようにしています。
clearTimeout
タイマー処理を停止しています。

clearTimeout(timerId);
pageIndex = 0;
isRunning = true;
displayScreen();
リセットボタンの処理
インデックスを0に戻して、最初から再スタートする処理です。
clearTimeout
タイマー処理を停止しています。
pageIndexを0にすることで最初からスタートするように再設定しています。
isRunning変数にtrueを設定することでdisplayScreen関数で動作するようにします。
displayScreenを実行してリセットとして処理を再開しています。




戻る

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