1

我正在尝试等待 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();                 

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

谢谢!

4

3 回答 3

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');

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

client . open(method, url [, async = true [, user = null [, password = null]]])
于 2013-07-10T19:32:51.967 回答
3

你不能。JavaScript 中没有“主动等待”,一次只能有一个主动执行(“单线程”)。

于 2012-08-01T12:47:34.587 回答
0

有一种解决方法。 而不是使用阻塞while 循环进行轮询,而是使用非阻塞setInterval ().. 所以你的代码可能看起来像这样。

 

    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+'"') 
      } 
     } 
    } 

    //Polling function 

    function checkEvent(){
    if(ajaxFinished == true){
    //your code i.e xmlhttp.open("GET", requestUrl, true);
    }
    clearInterval(chkeventid);//Clear Interval via ID for single time execution
    }

    var chkeventid=self.setInterval("checkEvent()",100);//The poll call

    The setInterval method is treated a bit differently in JS as you know so you may use it as against the while loop.
于 2012-08-01T13:37:59.653 回答