我有这个问题。 我有一个叫做functionA()的函数,它需要来自另一个函数functionB()的结果。javascript:等待退货
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;
}
我该怎么做让函数B完成befor继续执行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.");
}
}
};
}
如果您可以直接控制XMLHttpRequest对象,则可以将其设置为不是异步调用。否则,我会咨询你用来做ajax调用的库,把它变成一个同步调用或修改'functionB()'下面的代码作为对async'functionB()'调用的回调。 –
http://www.hunlock.com/blogs/Snippets:_Synchronous_AJAX – scrappedcola