-1

我有这个问题。例如,我有一个名为 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;
}

在继续执行函数A之前,我该怎么做才能让函数B完成?谢谢!

这是代码:

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.");
        }
    }
};
}
4

3 回答 3

1

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

  • 将您希望看到执行的代码移动到onreadystatechangeajax 请求的回调中,这样,在您收到响应之前它不会被执行

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

  • 使请求同步,但不推荐

  • 使用超时/间隔手动检查请求的就绪状态(蛮力,也不推荐)

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


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
}
于 2012-11-06T18:52:46.700 回答
0

当调用是异步的时,JavaScript 中不可能有睡眠/等待。您需要使用回调模式来执行此操作。

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

于 2012-11-06T18:46:14.923 回答
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.");
            }
        }
    };
}
于 2012-11-06T18:46:23.797 回答