Ajax等待数据返回时loading的显示

有时候Ajax处理的数据量比较大的时候,用户等待时间会比较长,如果这个时候不提示用户等待的话,用户可以会觉得很不耐烦。这里介绍一下如何在Ajax如何在处理数据时显示loading。

首先在HTML页面添加一个div层:

<div id="loading" style="color:#ffffff; display:none; position:absolute; top:80px; left:3em;"></div> 

这个div一开始是不显示的。

然后你可以在Ajax请求函数中添加如下代码:

xmlReq.onreadystatechange = function()  
{   
    var sliderBlank = document.getElementById("sidebar");
    // 让需要显示结果的层显示空白
    sliderBlank.innerHTML = " "; 
    
    // 获得loading显示层
    var loadingDiv = document.getElementById("loading"); 
    // 插入loading图
    loadingDiv.innerHTML = "<img src='images/loading.gif' />"; 
    // 显示loading层
    loadingDiv.style.display = ""; 
    if(xmlReq.readyState == 4)  
    {   
        // 数据处理完毕之后,将loading层再隐藏掉
        loadingDiv.style.display = "none"; 
        //alert(xmlReq.responseText);
        //document.getElementById('content2').innerHTML = xmlReq.responseText;   
        // 输出处理结果
        runXML(xmlReq.responseText);
    }   
}   

就是如此简单!

下面再附另一段参考代码:

xmlHttp.onreadystatechange = function(){
    //displace loading status
    var loadingDiv = document.getElementById("loading"); // get the div
    loadingDiv.innerHTML = "loading..."; // insert tip information
    loadingDiv.style.right = "0"; // set position, the distance to the right border of current document is 0px
    loadingDiv.style.top = "0"; // set position, the distance to the top border of current document is 0px
    loadingDiv.style.display = ""; // display the div
    //load completed
    if(xmlHttp.readyState == 4) {
        //hide loading status
        loadingDiv.style.display = "none"; // after completed, hidden the div again
        loadingDiv.innerHTML = ""; // empty the tip information
        //process response
        if(xmlHttp.status == 200) {
            var str = xmlHttp.responseText;
            /* do something here ! */
        }
        else
        alert("Error!" + "nStatus code is: " + xmlHttp.status + "nStatus text is: " + xmlHttp.statusText);
    }
}

转载:http://www.nowamagic.net/librarys/veda/detail/564

posted @ 2013-09-16 10:19  minimal  阅读(1602)  评论(0编辑  收藏  举报