我使用 $.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)”。我尝试使用 cookies 来完成最后一个操作,但“Items(0)”又出现了...
最佳答案
听起来像是 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);
}
}
关于php - jQuery (ajax) $.get 方法延迟结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4828033/