0

以下は、ajax を使用して、ページを更新せずに画像を動的に変更するコードです。

HTML

<img id="design" alt="" width="300" height="300"  />
<input type="button" id="GetImage" value="Get Image" />

Jクエリ

$(document).ready(function(){

$("#GetImage").click(function() {

    $.ajax({ //Make the Ajax Request
             type: "POST",
             url: "testimagelook.php", //file name
             success: function(server_response){
                var id = server_response;
                document.location.hash = id;
                $('#design').attr('src','img/boxes/'+id+'.png');
             }
    });
});

});

PHP ファイル testimagelook.php はデータベースに接続し、私の画像の 1 つのランダムな ID を返します。このコードは、画像を表示し、URL のハッシュに画像の ID を保存して、ユーザーの画像履歴を保存するのに問題なく機能します。ただし、ユーザーが戻るボタンをクリックしたときに、以前のハッシュ値を取得して正しい ID で画像をリロードする方法がわかりません。何か案は?

4

1 に答える 1

1

これを試して:

 $(document).ready(function(){

    if (document.location.hash) {
         updateImage();
    }

    $("#GetImage").click(function() {

         $.ajax({ //Make the Ajax Request
             type: "POST",
             url: "testimagelook.php", //file name
             success: function(server_response){
                var id = server_response;
                document.location.hash = id;
             }
         });
    });

    $(window).bind('hashchange',function(){
           updateImage();
    });

    function updateImage() {
         var id = document.location.hash.substring(1); // remove #
         $('#design').attr('src','img/boxes/'+id+'.png');
    }
});
于 2013-02-12T16:05:37.507 に答える