2013-02-12 60 views
0

下面是我的代碼,它使用ajax動態更改圖像而不刷新頁面。AJAX JQUERY檢索散列值

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重新加載圖像。有任何想法嗎?

回答

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

這個工作的魅力感謝您的幫助等。 (代碼缺失「});」從最後) – 2013-02-12 16:17:30

+0

另一個快速的問題。有沒有什麼辦法給他們提供一個鏈接到這個頁面,包括一個散列值來顯示圖像,例如「mysite.com/page.php#12」,如果他們複製並粘貼到瀏覽器中,它會顯示圖像ID 12? – 2013-02-12 16:20:35

+0

我更新了代碼來迎合這一點。看一看。 – 2013-02-12 16:26:27