【问题标题】:jQuery (ajax) $.get method delayed resultsjQuery (ajax) $.get 方法延迟结果
【发布时间】:2011-01-28 12:08:13
【问题描述】:

我正在使用 $.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)' 又出现了……

【问题讨论】:

    标签: php jquery ajax get


    【解决方案1】:

    听起来像是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);
        }
    }
    

    【讨论】:

    • 我希望它可以工作,不幸的是它没有。页面重新加载后,“Items(0)”仍然存在约 1 秒...感谢您的回答:)
    • 最后你的建议正是我所需要的!在我的代码中修复了一些其他内容(处理 updateStatus 超时)之后,localStorage 给出了解决方案。再次感谢!
    【解决方案2】:

    如果您的页面(调用fetchnew() 的页面)是用PHP 呈现的,请调用Ajax 文件(new-items.php) 调用的相同函数。这样,您的内容就会立即出现。

    【讨论】:

    • 我正在为当前工作站点开发一个模块,所以我无法更改页面本身,只能通过我的代码更改其组件(这就是使用 jquery 的原因)。谢谢回复:)
    猜你喜欢
    • 2013-12-25
    • 1970-01-01
    • 2021-12-02
    • 2013-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多