我一直在使用jQuery創建圖像查看器,並且我設法通過使用ajax來調用我的PHP代碼以獲取圖像的新ID,從而使圖像動態顯示。當用戶點擊按鈕時,圖像將顯示其相關信息,但是如果它們導航回來,則只有圖像發生更改,因爲其他信息未保存在散列內。使用哈希處理數據
我試過使用ajax post調用來獲取哈希ID的信息,但是當我這樣做時,它通過圖像回收像一個外觀,這不是我想要的。我的代碼如下:
HTML
<img id="design" alt="" width="300" height="300" /><br>
<span id="lblName" name="lblName"></span><br>
<input type="button" id="GetImage" value="Get Image" />
jQuery的
$(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){
$.getJSON("testimagelook.php", function(data) {
var id = data.id;
document.location.hash = id;
$("#lblName").html(data.name);
$("#lblRating").html(data.average + " (" + data.votes + ") (<a href='User.php?uid=" + data.userid + "'>" + data.username + "</a>)");
});
}
});
});
$(window).bind('hashchange',function(){
updateImage();
});
function updateImage() {
var id = document.location.hash.substring(1); // remove #
$('#design').attr('src','img/boxes/'+id+'.png');
}
});
的PHP文件從JSON格式的數據庫返回一個隨機行。
編輯
下面的函數(updateImage())已更改,但不工作:
function updateImage() {
var id = document.location.hash.substring(1); // remove #
if(known_images[id]==null){
$.ajax({ //Make the Ajax Request
type: "POST",
url: "testimagelook.php", //file name
data: {boxid: id},
success: function(server_response){
$.getJSON("testimagelook.php", function(data) {
var id = data.id;
known_images[id] = [];
known_images[id] ['name'] = data.name;
known_images[id] ['average'] = data.average;
known_images[id] ['votes'] = data.votes;
known_images[id] ['username'] = data.username;
known_images[id] ['userid'] = data.userid;
});
}
});
}
$('#design').attr('src','img/boxes/'+id+'.png');
$("#lblName").html(known_images[id]['name']);
$('#lblRating').html(known_images[id] ['average'] + " (" + known_images[id] ['votes'] + ") (<a href='User.php?uid=" + known_images[id] ['userid'] + "'>" + known_images[id] ['username'] + "</a>)");
}
爲什麼要向同一個URL發送兩個後續的Ajax請求(一個使用POST,一個使用GET)? – Bergi 2013-02-14 13:04:28
@Bergi我目前只使用一個POST請求,但如果我點擊我的瀏覽器後退按鈕,我可以得到的唯一信息是id(來自URL中的哈希),因此將不得不做另一個Ajax請求來獲取其他這個ID的信息。 – 2013-02-14 13:17:09
沒有你使用TWO'$ .ajax'作爲ONE,'$ .getJSON'是另一個(最有可能響應相同的數據)。我想你的意思是使用:var data = $ .parseJSON(server_response);'而不是 – itsid 2013-02-14 13:30:56