开发者

Loading gif "freezes" when code is executing

I'm appending an animated开发者_开发百科 gif which is a loading bar. The gif is defined earlier in the code and I then just do the following..

document.getElementById("loading").style.display = "inline";
//some if statements.
do_ajax(params);

The ajax call looks something like...

    var uri = getURL(params);
    var xhr = new XMLHttpRequest();
    xhr.open("POST",uri,false);
    xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
    xhr.send(null);

to show the loading gif. I then perform some checks (if statements) followed by an AJAX request. However, the gif freezes while all this code is executing and only begins to 'move' once the code has finished executing. Why is this? How do I fix this issue?

I'm using Chrome 11


You are using synchronous XHR. This will lock the browser whilst waiting for the request to finish. Obviously, it causes a serious UI issue.

Try asynchronous. Set open()'s 3rd parameter to true. You also need to assign the readystatechange event and listen for success.

Further Reading.


I guess just make sure you are using async: true

    $("#wait").show(); //SHOW WAIT IMG

     $.ajax({
        url: 'process.php',  //server script to process data
        type: 'POST',
        async: true, // <<<<< MAKE SURE IT'S TRUE
        data: { data1: "y", data2: "m", data3: "x" },
        complete: function() {
            $("#wait").hide();
        },        

        success: function(result) {
            //do something
        }
    });


Are you expecting to see the loading.gif while your synchronous ajax request is running?

Synchronous ajax requests completely lock up the UI of most browsers, preventing any changes you make from being displayed until the request completes.

If you want to see loading.gif while the request is running, make it asynchronous:

//--- js code

document.getElementById("loading").style.display = "inline";

//--- js code

var uri = getURL(params);
xmlhttp.open("POST", uri, true);
xmlhttp.onreadystatechange = handleReadyStateChange;
xmlhttp.send(null);
function handleReadyStateChange() {
    if (xmlhttp.readyState == 4) {
        // Request Complete
    }
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜