php - jQuery (ajax) $.get 方法延迟结果

标签 php jquery ajax get

我使用 $.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/

相关文章:

javascript - 使用帖子循环将 Wookmark tile 插件应用于 wordpress 主题

javascript - 在类中使用 getJSON(范围问题)

php - 如何在文本框上显示光标第一行

php - 了解单元测试

javascript - Laravel 中 VueJS 组件实现中的鼠标悬停

php - 选择数据库中具有多个实例的用户

php - 如何调试 IE9 JQuery AJAX 缓存问题?

php - 无法选择动态生成的表单元素(ajax)

javascript - 学习Ajax : Dynamic content not loading

php - 数据库 :Could not connect to MySQLDatabase in joomla 1. 5