2011-01-28 89 views
2

我使用$ .get()從php腳本中獲取一些元素,然後通過將它們寫入div來顯示結果。這是定期完成的,以及當div被點擊或頁面重新加載時。代碼如下:

function fetchnew(){ 

    var status = $J.cookie("status_on"); 

    if (status == 'on'){ 
    //fetch new items 
    //results from new-items.php have this format: 
    //<p>Item1</p><p>Item2</p>... 
    $J.get(modulebaselink+'new-items.php', '', function(newitems){ 
     $J('#content').html(newitems); 
     updatestatus(); 
     }); 
    } 
fetchnew_timeout = setTimeout('fetchnew();', refresh_rate); 
}//end fetchnew() 

function updatestatus(){ 

    var status = $J.cookie("status_on"); 

    if (status == 'on'){ 
     //Show number of loaded items 
     var totalItems=$J('#content p').length; 
     $J('#status').html("Items ("+totalItems+")"); 

    } 
} 

我的問題是#status內容在頁面重新載入後顯示一些延遲。當頁面加載時,我得到'Items(0)'約1秒,然後0改變爲實際值。在顯示實際值之前,有什麼方法可以使'Items(0)'無效?或者至少,在'Items(new_value)'出現之前緩存先前的值並顯示'Items(old_value)'而不是'Items(0)'。我嘗試了Cookie來做最後一個,但是'Items(0)'再次出現...

回答

2

聽起來像localStorage的合理用例。擴展updatestatus()這樣的:

// this should be called at some entry point of your script 
var ls_available = 'localStorage' in window; 

if(ls_available && localStorage.getItem('totalItems')) 
    $J('#status').html("Items ("+localStorage.getItem('totalItems')+")"); 

function updatestatus(){ 
    var status = $J.cookie("status_on"); 

    if (chat_status == 'on'){ 
     var totalItems=$J('#content p').length; 
     $J('#status').html("Items ("+totalItems+")"); 

     if(ls_available) localStorage.setItem('totalItems', totalItems); 
    } 
} 
+0

我希望它可以工作,但不幸的是它沒有。 '項目(0)'仍然存在約1秒後頁面重新加載...感謝您的回答:) – CrisDeBlonde 2011-01-28 13:30:28

0

如果您的頁面(調用fetchnew()的那個頁面)在PHP中呈現,請調用與Ajax文件(new-items.php)電話。那樣,你的內容就會立即出現。

+0

我工作了當前工作點的模塊上,這樣我就可以不通過我的代碼更改頁面本身,只是它的組成部分(這就是爲什麼使用jQuery)。 感謝您回覆:) – CrisDeBlonde 2011-01-28 13:59:20