简体   繁体   English

ajax同步调用问题

[英]ajax synchronous call problem

I have an Ajax function which looks like:我有一个 Ajax function 看起来像:

  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; }
     return __data;      
  } else {
     return false;
  }      
}

then i have very simple loading function ( an loading image must appear in center of page ):然后我有非常简单的加载 function (加载图像必须出现在页面中心):

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

then how i call ajax function:那我怎么称呼 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..open调用中使用async = true

Bind an eventhandler to readystatechange .将事件处理程序绑定到readystatechange If the readystate is 4 (LOADED) then get the data and send it to your callback.如果readystate为 4 (LOADED),则获取数据并将其发送到您的回调。

If the AJAX fails call the callback with null or false .如果 AJAX 失败,则使用nullfalse调用回调。

In your callback get the loadedData and either render it or throw an error if there is no data.在您的回调中获取loadedData并渲染它,或者如果没有数据则抛出错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM