简体   繁体   中英

AJAX JQUERY Retrieving hash value

Below is my code using ajax to dynamically change the image without refreshing the page.

HTML

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

JQUERY

$(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');
             }
    });
});

});

The php file testimagelook.php connects to the database and brings back a random id of one of my images. This code works fine for showing the image and saving the id of the image in the hash of the URL allowing me to preserve the users history of images. However I am unsure on how I would retrieve the previous hash value and reload the image with the correct id when the user clicks the back button. Any ideas?

Try this:

 $(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');
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM