问题描述
|
我不清楚以下伪代码的返回值:
function foo()
var ret = 0;
var xhr=send_request( \"bla\",function() {
// do something with the AJAX response
// based on the value of response,var ret get set
} );
return ret;
}
我想要实现的是:基于AJAX响应,我可能决定再次尝试该请求。但是上面的函数总是返回0。
显然,我可以使foo()函数决定在需要时两次调用send_request(),但这有点难看。有没有简单而不错的方法来做到这一点?
谢谢
解决方法
您正在尝试同步进行ajax调用,但是正在进行异步调用。
重要的是要了解,编写方式后,代码不会等待AJAX调用完成才继续进行下一行。因此,它总是返回
ret
的初始值。
做一些事情来解决这个问题:
使用jQuery(如果尚未使用)
使用jQuery \的ajax()函数,并将async
设置为false。
应该看起来像这样:
function foo()
var ret = $.ajax({ url: \"blah\",async: false
}).responseText;
// do your stuff here
return ret;
}
编辑:可以通过异步调用来执行此操作,但是您必须调整对问题的思考方式。不必考虑返回值,而必须考虑回调函数。
例如,假设我正在尝试获取用户名并将其放在页面上。我的代码如下所示:
function GetUsername() {
$.ajax( { url: \"blah\",success: PopulateUsername // Specify a callback
});
// I don\'t do anything else. Execution will continue when the
// callback gets called from the AJAX call.
}
function PopulateUsername(data) {
alert(data);
// Anything else I want to do,I do here,because it is only
// here that I have access to the result.
}
GetUsername(); // I call GetUsername() here,and that\'s it. Any
// further actions that need to happen are going to
// occur in the callback function
, 变量“ 1”在函数中具有局部作用域。因此,每次调用它时,变量都会初始化为0。
此外,当函数返回变量ret
时,send_request
函数(将其他内容设置为ret
)尚未运行,由于返回的值始终为0。必须在返回函数后ajax请求完成send_request
功能将新值设置为ret
。
, 如果要保持同步,请使用Stargazer712的建议。
您可以尝试通过以下方式使事情保持异步:
function foo(callback)
var xhr=send_request( \"bla\",function(result) {
callback(result)
} );
}
function test(result) {
// test result here
if(result != \"what I want\")
foo(test); // repeat the ajax call under certain conditions
else
alert(\"got it\");
}
$(function() {
foo(test);
});
这将重复ajax请求,直到响应与某个值匹配为止。
, 您不希望从将要进行AJAX调用的函数中返回值,因为AJAX请求在该函数返回之前尚未完成(而且我个人不同意答案,即您应该设置异步为假)。您想要执行以下操作:
function retFunction(val) {
// Do something here for various values of val
if (val == 0) {
// Something
} else if (val == 1) {
// Something else
}
}
function foo()
var xhr=send_request( \"bla\",function() {
var myResult = 0; // Something here based on return values.
retFunction(myResult);
});
}