开发者

Showing a div while page is loading, hiding when its done

I want to show a div with a loading animation over my page while the page loads some XML content. Once its loaded, I want to hide this div.开发者_Python百科 How can I go about doing this?


$.ajax({
    url: '/test.xml',
    beforeSend: function(XMLHttpRequest) {
        // Show the div before sending the request
        $('#load').show();
    },
    complete: function(XMLHttpRequest, textStatus) {
        // Hide the div no matter if the call succeeded or not
        $('#load').hide();
    },
    success: function(xml) {
        // if the request succeeds do something with the received XML           
    }
});


$.ajax({
    type: "GET",
    url: "your.xml",
    dataType: "xml",
    beforeSend: function() {
        $('#div').fadeIn();
    },
    success: function(xml) {
       // example for parsing xml
       $(xml).find('YOUR_XML_TAG').each(function(){
           // append xml to page HERE
       });
    },
    complete: function() {
       $('#div').fadeOut();
    }
});


@cballou Your code will leave '#div' "up", if $.ajax() has not suceeded for any of numerous possible reasons.


Almost right ;) Never under-estimate the importance of removing redundant $() calls. So ...

//all of this is inside some closure or function
var $blanket = $("#div") ; 
// check if after last call, something has possibly removed your '#div'
// throw if false
ASSERT( $blanket.length === 1 ) ;    
$.ajax({
        type: "GET",
        url: "your.xml",
        dataType: "xml",
        beforeSend: function() {  $blanket.fadeIn();
        },
        success: function(xml) {
           // example for parsing xml
           $(xml).find('YOUR_XML_TAG').each(function(){
               // append xml to page HERE
           });
        },
        complete: function() { $blanket.fadeOut();
        }
    });

--DBJ


I would use the onbeforeunload event fired when the page URL changes, to create an overlay div with opacity at 0.5, which will be replaced by the new content when the page is loaded.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜