显示LOADING直到页面完全加载

时间:2012-04-24 15:07:35

标签: javascript ajax

我有这个javascript:

function createRequestObject(){
    var req;
    if(window.XMLHttpRequest){
        //For Firefox, Safari, Opera
        req = new XMLHttpRequest();
    }
    else if(window.ActiveXObject){
        //For IE 5+
        req = new ActiveXObject("Microsoft.XMLHTTP");
    }
    else{
        //Error for an old browser
        alert('Your browser is not IE 5 or higher, or Firefox or Safari or Opera');
    }
    //alert (req);
    return req;
}

//Make the XMLHttpRequest Object
var http = createRequestObject();

function sendRequestTwo(method, url, head1){
    head = head1
    if(method == "get" || method == "GET"){
        http.open(method,url);
        http.onreadystatechange = handleResponseTwo;
        http.send(null);

    }
}

var head; //divs name

function handleResponseTwo(){
    if(http.readyState == 4 && http.status == 200){
        var response = http.responseText;
        if(response){  
            document.getElementById(head).innerHTML = response;
        }
    }      
}

这部分

            document.getElementById(head).innerHTML = response;

将结果粘贴回我的页面。 如何在页面完全加载之前显示“正在加载”?

3 个答案:

答案 0 :(得分:3)

如果在你的身体中加载Html就像

一样
<div id="loadingDiv" class="hiddenClass">Fancy rotating image goes here</div>

有一个css类,显示display:none;那么你可以在

之前使用它
http.onreadystatechange = handleResponseTwo;
var myDiv = document.getElementById('loadingDiv');
myDiv.className = "showClass";

之后

document.getElementById(head).innerHTML = response;

添加

var myDiv = document.getElementById('loadingDiv');
myDiv.className = "hiddenClass";

一起

function createRequestObject(){
    var req;
    if(window.XMLHttpRequest){
        //For Firefox, Safari, Opera
        req = new XMLHttpRequest();
    }
    else if(window.ActiveXObject){
        //For IE 5+
        req = new ActiveXObject("Microsoft.XMLHTTP");
    }
    else{
        //Error for an old browser
        alert('Your browser is not IE 5 or higher, or Firefox or Safari or Opera');
    }
    //alert (req);
    return req;
}

//Make the XMLHttpRequest Object
var http = createRequestObject();

function sendRequestTwo(method, url, head1){
    head = head1
    if(method == "get" || method == "GET"){
        var myDiv = document.getElementById('loadingDiv');
        myDiv.className = "showClass";

        http.open(method,url);
        http.onreadystatechange = handleResponseTwo;
        http.send(null);

    }
}

var head; //divs name

function handleResponseTwo(){
    if(http.readyState == 4 && http.status == 200){
        var response = http.responseText;
        if(response){  
            document.getElementById(head).innerHTML = response;
            var myDiv = document.getElementById('loadingDiv');
            myDiv.className = "hiddenClass";
        }
    }      
}

答案 1 :(得分:1)

我不知道HTML的详细信息,但您是否只能将加载放入包含id="head"的标记中?

然后当您更新innerHTML时,将自动替换加载。如果您有更多要求,请说明。

答案 2 :(得分:1)

您可以在sendRequestTwo

时将正在加载打印到Head div中