当同步选项不可用时,如何等待ajax请求在javascript中完成?

Mar*_*cka 1 javascript ajax

我正在尝试等待AJAX​​请求完成。如果该方法xmlhttp.open支持async = false但Ant Galio不支持此选项,并且仅允许异步请求,将很容易。问题是我如何等待回调被调用。

    var ajaxFinished = false;
    var xmlhttp = new XMLHttpRequest();
    this.debug("-- onreadystatechange is being defined");
    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == 4) {
            ajaxFinished = true;
                var data = xmlhttp.responseText;
            if (xmlhttp.status == 200) {
                that.debug('downloadSettings: SUCCESS');
                [...]
            } else {
                that.debug('downloadSettings:');
                that.debug('-- Error: ');
                that.debug('-- ResponseText: "'+data+'"')
            }
        }
    }

    while (ajaxFinished == false) {

    }

    this.debug("-- open connection");
    xmlhttp.open("GET", requestUrl, true); /* Ant Galio does not support synchronous  */
    this.debug("-- send");
    xmlhttp.send();                 
Run Code Online (Sandbox Code Playgroud)

我正在寻找某种积极的等待。我知道另一种解决方案,但是我对一种解决方案感兴趣,该解决方案与上面的示例相比,无需更改更多代码。

谢谢!

Tit*_*100 5

是的你可以

function getFile(url) {
  if (window.XMLHttpRequest) {              
    AJAX=new XMLHttpRequest();              
  } else {                                  
    AJAX=new ActiveXObject("Microsoft.XMLHTTP");
  }
  if (AJAX) {
     AJAX.open("GET", url, false);                             
     AJAX.send(null);
     return AJAX.responseText;                                         
  } else {
     return false;
  }                                             
}

var fileFromServer = getFile('http://somedomain.com/somefile.txt');
Run Code Online (Sandbox Code Playgroud)

w3c定义http://www.w3.org/TR/XMLHttpRequest/#the-open()-方法

client . open(method, url [, async = true [, user = null [, password = null]]])
Run Code Online (Sandbox Code Playgroud)