【问题标题】:AJAX JQUERY Retrieving hash valueAJAX JQUERY 检索哈希值
【发布时间】:2013-01-27 23:46:45
【问题描述】:

下面是我使用ajax动态改变图片而不刷新页面的代码。

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

});

php 文件 testimagelook.php 连接到数据库并带回我的一张图像的随机 ID。此代码适用于显示图像并将图像的 id 保存在 URL 的哈希中,从而允许我保留图像的用户历史记录。但是,当用户单击后退按钮时,我不确定如何检索先前的哈希值并使用正确的 id 重新加载图像。有什么想法吗?

【问题讨论】:

    标签: javascript jquery ajax hash


    【解决方案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');
        }
    });
    

    【讨论】:

    • 这就像一个魅力感谢您的帮助。 (代码缺少“});”从头到尾)
    • 另一个快速的问题。有什么方法可以为他们提供指向此页面的链接,包括显示图像的哈希值,例如“mysite.com/page.php#12”,如果他们将其复制并粘贴到浏览器中,它将显示图像id 12?
    猜你喜欢
    • 2017-06-10
    • 2014-01-02
    • 1970-01-01
    • 2013-10-18
    • 1970-01-01
    • 2010-12-21
    • 2017-10-04
    • 2010-12-29
    • 2013-08-29
    相关资源
    最近更新 更多