javascript:等待回归

时间:2012-11-06 18:43:30

标签: javascript ajax

我有这个问题。 我有一个函数,例如名为functionA(),需要另一个名为functionB()的函数的结果。

var globalVar="";
function functionA(){
    //...
    functionB();
    //here i have to use the global variable (that is empty because functionB isn't finished)
}
function functionB(){
    //ajax request
    globalVar=ajaxRequest.responseText;
}

如何让functionB完成继续执行functionA? 谢谢!

这是代码:

var ingredientiEsistenti="";
function ShowInserisciCommerciale() {
    getElementiEsistenti();
    JSON.parse(ingredientiEsistenti);
}

function getElementiEsistenti(){

// prendo gli ingredienti esistenti.
var url = "http://127.0.0.1:8080/Tesi/Ingredienti";
var xmlHttp = new XMLHttpRequest();
xmlHttp.open("POST", url, false);
xmlHttp.send(null);
xmlHttp.setRequestHeader("Content-type",
        "application/x-www-form-urlencoded");
xmlHttp.onreadystatechange = function() {
    if (xmlHttp.readyState == 4) // COMPLETED
    {
        if (xmlHttp.status == 200) // SUCCESSFUL
        {
            ingredientiEsistenti = xmlHttp.responseText;
        } else {

            alert("An error occurred while communicating with login server.");
        }
    }
};
}

3 个答案:

答案 0 :(得分:1)

您有许多选项之一,不需要 evil 全局变量:

  • 将您要执行的代码移动到ajax请求的onreadystatechange回调中,这样,在您收到回复之前,它不会被执行

  • 重新定义functionA,以便它需要一个允许您跳过第一位的参数:

  • 请求同步,不推荐,但

  • 使用超时/间隔手动检查请求的readystate(蛮力,不推荐)

  • 也许在你的特定情况下,也有一些工人诡计可以做到这一点


function functionA(skipDown)
{
    skipDown = skipDown || false;
    if (skipDown === false)
    {
        //doStuff
        return functionB();//<-- call functionA(true); from the readystatechange callback
    }
    //this code will only be called if skipDown was passed
}

答案 1 :(得分:0)

当调用异步时,在JavaScript中无法进行休眠/等待。您需要使用回调模式来执行此操作。

可以使XMLHttpRequest同步,但这可能会导致其他问题。它可以挂起浏览器,因为它会阻止所有其他操作发生。因此,如果您想显示加载动画,则很可能无法执行。

答案 2 :(得分:0)

您可以使AJAX请求同步。 https://developer.mozilla.org/en-US/docs/DOM/XMLHttpRequest/Synchronous_and_Asynchronous_Requests

var request = new XMLHttpRequest();
// Last parameter makes it not asnychronous
request.open('GET', 'http://www.mozilla.org/', false); 
request.send(null);
// Won't get here until the network call finishes
if (request.status === 200) {
  console.log(request.responseText);
}

但是,这会在等待服务器响应时阻止UI,这几乎不是你想要的。在这种情况下,您应该使用回调来处理结果。

这是一个使用回调而不依赖于全局变量的示例。你应该总是逃避那些

function ShowInserisciCommerciale(  ) {
    getElementiEsistenti(function(responseText) {
        JSON.parse(responseText);
    });
}

function getElementiEsistenti(successCallback){
    var url = "http://127.0.0.1:8080/Tesi/Ingredienti";
    var xmlHttp = new XMLHttpRequest();
    xmlHttp.open("POST", url, false);
    xmlHttp.send(null);
    xmlHttp.setRequestHeader("Content-type",
            "application/x-www-form-urlencoded");
    xmlHttp.onreadystatechange = function() {
        if (xmlHttp.readyState == 4) // COMPLETED
        {
            if (xmlHttp.status == 200) // SUCCESSFUL
            {
                successCallback(xmlHttp.responseText); 

            } else {

                alert("An error occurred while communicating with login server.");
            }
        }
    };
}