开发者

Ajax loading graphic

So I'm no JavaScript genius, but I can follow a tutorial just fine. I've got my Ajax JavaScript request. How do I make it so that I can make a .gif animation show while the information is being requested? Here's the code:

function ajaxFunction(){
    var ajaxRequest;  // The variable that makes Ajax possible!

    try{
        // Opera 8.0+, Firefox, Safari
        ajaxRequest = new XMLHttpRequest();
    } catch (e){
        // Internet Explorer Browsers
        try{
            ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
            try{
                ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e){
                // Something went wrong
                alert("Your browser broke!");
                return false;
            }
        }
    }
    // Create a function that will receive data sent from the server
    ajaxRe开发者_开发技巧quest.onreadystatechange = function(){
        if(ajaxRequest.readyState == 4){
            var ajaxDisplay = document.getElementById('confirm');
            ajaxDisplay.innerHTML = ajaxRequest.responseText;
        }
    }
    var number = document.getElementById('number').value;
    var message = document.getElementById('message').value;
    var queryString = "?number=" + number + "&message=" + message;
    ajaxRequest.open("GET", "sms.php" + queryString, true);
    ajaxRequest.send(null); 
}

The name of the GIF file is ajax-loader.gif.

I know this can be done easily with jQuery, but I can only use straight, original JavaScript code for this, not extra libraries.


When you start the AJAX request, add an img element:

var image=document.createElement('img');
image.setAttribute('src', 'ajax-loader.gif');
document.getElementsByTagName('body')[0].appendChild(image);

When the AJAX request is done, remove it. (this code assumes image is still in scope)

image.parentNode.removeChild(image);


If you can, I would avoid using this methodology for your XHR requests. I would use jQuery or some other framework. They provide you many more tested options that you can code yourself in any reasonable amount of time. http://api.jquery.com/jQuery.ajax/ is a good place to start. You can use the beforeSend and the afterSend events.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜