ページが読み込まれた後に PHP 変数をインクリメントすることはできません。JavaScript を使用してクライアント側でインクリメントしようとしています。ページを更新せずにこれを行う場合は、AJAX を使用してその PHP を呼び出す必要があります。その場合でも、JavaScript 変数をインクリメントして現在の場所を追跡する必要があります。
編集: PHP と JavaScript、具体的には jQuery ライブラリを使用して ajax ルーチンを作成することに少し夢中になりました。これを機能させるにはリンクする必要があります。達成しようとしていることに合わせてスクリプトの一部を変更する必要がある場合もありますが、これは確かに、期待どおりに ajax アプリを実行するためのガイドです。
次のスクリプトで PHP ファイルを作成することから始めます。
<?php
// Set content header to json
header('Content-Type: application/json');
// Get the index from the AJAX
$index = $_GET['index'];
// Grab file contents & parse
$html = file_get_contents("http://www.9gag.com");
preg_match_all( '|http://d24w6bsrhbeh9d\.cloudfront\.net/photo/.+?\.jpg|', $html, $gags);
// Send filename back to AJAX script as JSON
echo json_encode(array($gags[0][$index]));
?>
次に、HTML にこの jQuery を含めて、PHP スクリプトへの AJAX 呼び出しを完了し、PHP スクリプトからのデータで DOM を更新します。
<script>
$(function() {
'use strict';
// Initiate index variable
var index = 0;
// Load initial image
loadImage(index);
// Add click event to a button with class of next-btn
$('.next-btn').click(function(e) {
e.preventDefault();
// Increment index to get next image
index++;
// Run AJAX function to retrieve image
loadImage(index);
});
// Add click event to a button with class prev-btn
$('.prev-btn').click(function(e) {
e.preventDefault();
// Decrement the index if it isn't 0
if (index > 0) {
index--;
}
// Run AJAX function to retrieve image
loadImage(index);
});
});
function loadImage(index) {
'use strict';
$.ajax({
type: 'GET',
url: 'your-php-script.php', // Filepath to your PHP script
data: 'index='+index, // Index is passed through GET request
dataType: 'json', // Return JSON
success: function (data) { // If the php script succeeds
// Change img with class of pic's src
// to the filename retrieved from php
$('.pic').attr('src', data[0]);
}
});
}
</script>
必要に応じてこれを構成するには、ある程度のデバッグが必要になる可能性があるため、PHP と jQuery/JavaScript に関するある程度の知識が必要です。幸運を!
EDIT 2:ダウンロードしたい場合は、動作中の(テスト済み、動作する)ソースファイルを私のWebサイトにアップロードしました。回答を受け入れて、ファイルを取得したことをお知らせください...
http://www.wedgewebdesign.com/files/ajax-image-loader.zip