如何等待AJAX​​请求完成在JavaScript时同步选项不可用? [英] How to wait for ajax request to complete in javascript when synchronous option is not available?

查看:135
本文介绍了如何等待AJAX​​请求完成在JavaScript时同步选项不可用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想等待AJAX​​请求完成。这将是容易,如果该方法 xmlhttp.open 将支持异步=假,但蚂蚁Galio不支持此选项,只有异步请求被允许。现在的问题是我怎么能等待回调被调用。

I'm trying to wait for the AJAX request to complete. 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();                 

我在寻找某种积极的等待。我知道的另一种解决方案,但我感兴趣的是一个解决方案,不要求改变更多的code比我上面的例子。

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.

谢谢!

推荐答案

您不能。有在JavaScript没有活性等待,只能有一个活动的执行时间(单线程)。

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

这篇关于如何等待AJAX​​请求完成在JavaScript时同步选项不可用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆