开发者

ajax synchronous call problem

I have an Ajax function which looks like :

  function getData(p) {
  loadingImage();
  p = p.replace("frame_", "");
  if (window.XMLHttpRequest) {              
    AJAX=new XMLHttpRequest();              
  } else {                                  
    AJAX=new ActiveXObject("Microsoft.XMLHTTP");
  }
  if (AJAX) {
     var __page =encodeURIComponent(p);
     AJAX.open("GET", "page.php?page="+__page, false);                             
     AJAX.send(null);
     var __data = AJAX.responseText.match(/<data>[\s\S]*?<\/data>/gmi);
     if(!__data) { return false; }
   开发者_StackOverflow  return __data;      
  } else {
     return false;
  }      
}

then i have very simple loading function ( an loading image must appear in center of page ) :

function loadingImage(type)
{
   document.getElementById("body").innerHTML = "<div class='loading'></div>";
}

then how i call ajax function :

 var loadedData = getData("home");
 if(loadedData)
 {
   document.getElementById("body").innerHTML = loadedData;
 }
 else
 {
  document.getElementById("body").innerHTML = "Error";
 }

but the loading image won't appear, it's quite simple, but i'm stuck here , how make it to show that loading image while requesting data, then to replace loading image with loaded data. Thanks


function getData(p, cb) {
    loadingImage();
    p = p.replace("frame_", "");
    if (window.XMLHttpRequest) {
        AJAX = new XMLHttpRequest();
    } else {
        AJAX = new ActiveXObject("Microsoft.XMLHTTP");
    }
    if (AJAX) {
        var __page = encodeURIComponent(p);
        AJAX.open("GET", "page.php?page=" + __page, true);
        AJAX.onreadystatechange = function(e) {
            if (AJAX.readystate === 4) {
                var __data = AJAX.responseText.match(/<data>[\s\S]*?<\/data>/gmi);
                cb(data);
            }
        };
        AJAX.send(null);
    } else {
        cb(null);
    }
}

getData("home", function(loadedData) {
    if (loadedData) {
        document.getElementById("body").innerHTML = loadedData;
    }
    else {
        document.getElementById("body").innerHTML = "Error";
    }
});

Use async = true in the .open call.

Bind an eventhandler to readystatechange. If the readystate is 4 (LOADED) then get the data and send it to your callback.

If the AJAX fails call the callback with null or false.

In your callback get the loadedData and either render it or throw an error if there is no data.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜