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

3

できません。JavaScript には「アクティブ待機」はありません。アクティブな実行は一度に 1 つだけです (「シングルスレッド」)。

于 2012-08-01T12:47:34.587 に答える
0

回避策があります。pollにブロックする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 に答える