开发者

jQuery (ajax) $.get method delayed results

开发者 https://www.devze.com 2023-02-07 01:21 出处:网络
i\'m using $.get() to get some elements from a php script and then show the results by \"writing\" them into a div. This is done periodically, as well as when the div is clicked or when the page reloa

i'm using $.get() to get some elements from a php script and then show the results by "writing" them into a div. This is done periodically, as well as when the div is clicked or when the page reloads. Here's the code:

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+")");

   }
}

My problem is that the #status contents display with some delay after page reload. When the page loads i get 'Items(0)' for about ~1 sec, and then 0 changes to the real value. Is there any way to void the 'Items(0)' before displaying the real value? Or at 开发者_JS百科least, cache the previous value and display 'Items(old_value)' instead of 'Items(0)' before the 'Items(new_value)' appears. I tried cookies to do the last one, but 'Items(0)' was there again...


Sounds like a reasonable usecase for the localStorage. Extend updatestatus() like this:

// 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);
    }
}


If your page (the one where fetchnew() is called) is rendered in PHP, call the same function that the Ajax file (new-items.php) calls. That way, your content is there immediately.

0

精彩评论

暂无评论...
验证码 换一张
取 消