最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

How to wait for ajax request to complete in javascript when synchronous option is not available? - Stack Overflow

programmeradmin1浏览0评论

I'm trying to wait for the AJAX request to plete. It would be easy if the method xmlhttp.open would support async = false but Ant Galio does not support this option and only asynchronous requests are permitted. The question is how can I wait for the callback to be called.

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

I'm looking for some kind of active waiting. I know about another solution but I'm interested in a solution that would not require changing more of the code than is my example above.

Thanks!

I'm trying to wait for the AJAX request to plete. It would be easy if the method xmlhttp.open would support async = false but Ant Galio does not support this option and only asynchronous requests are permitted. The question is how can I wait for the callback to be called.

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

I'm looking for some kind of active waiting. I know about another solution but I'm interested in a solution that would not require changing more of the code than is my example above.

Thanks!

Share Improve this question edited Aug 1, 2012 at 12:49 Bergi 665k161 gold badges1k silver badges1.5k bronze badges asked Aug 1, 2012 at 12:41 MartyIXMartyIX 28.7k32 gold badges139 silver badges217 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 5

yes, you can

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./somefile.txt');

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

client . open(method, url [, async = true [, user = null [, password = null]]])

You can't. There is no "active waiting" in JavaScript, there can be only one active execution a time ("single-threaded").

There is a workaround. Instead of using the the blocking while loop for poll use the nonblocking setInterval().. so your code might look something like this.

 

    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.

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论
ok 不同模板 switch ($forum['model']) { /*case '0': include _include(APP_PATH . 'view/htm/read.htm'); break;*/ default: include _include(theme_load('read', $fid)); break; } } break; case '10': // 主题外链 / thread external link http_location(htmlspecialchars_decode(trim($thread['description']))); break; case '11': // 单页 / single page $attachlist = array(); $imagelist = array(); $thread['filelist'] = array(); $threadlist = NULL; $thread['files'] > 0 and list($attachlist, $imagelist, $thread['filelist']) = well_attach_find_by_tid($tid); $data = data_read_cache($tid); empty($data) and message(-1, lang('data_malformation')); $tidlist = $forum['threads'] ? page_find_by_fid($fid, $page, $pagesize) : NULL; if ($tidlist) { $tidarr = arrlist_values($tidlist, 'tid'); $threadlist = well_thread_find($tidarr, $pagesize); // 按之前tidlist排序 $threadlist = array2_sort_key($threadlist, $tidlist, 'tid'); } $allowpost = forum_access_user($fid, $gid, 'allowpost'); $allowupdate = forum_access_mod($fid, $gid, 'allowupdate'); $allowdelete = forum_access_mod($fid, $gid, 'allowdelete'); $access = array('allowpost' => $allowpost, 'allowupdate' => $allowupdate, 'allowdelete' => $allowdelete); $header['title'] = $thread['subject']; $header['mobile_link'] = $thread['url']; $header['keywords'] = $thread['keyword'] ? $thread['keyword'] : $thread['subject']; $header['description'] = $thread['description'] ? $thread['description'] : $thread['brief']; $_SESSION['fid'] = $fid; if ($ajax) { empty($conf['api_on']) and message(0, lang('closed')); $apilist['header'] = $header; $apilist['extra'] = $extra; $apilist['access'] = $access; $apilist['thread'] = well_thread_safe_info($thread); $apilist['thread_data'] = $data; $apilist['forum'] = $forum; $apilist['imagelist'] = $imagelist; $apilist['filelist'] = $thread['filelist']; $apilist['threadlist'] = $threadlist; message(0, $apilist); } else { include _include(theme_load('single_page', $fid)); } break; default: message(-1, lang('data_malformation')); break; } ?>