参见英文答案 > How do I return the response from an asynchronous call? 35个
我有一个函数,它使用var关键字声明一个变量.然后它启动一个AJAX请求来设置变量的值,然后从该函数返回该变量.
但是,我的实现失败了,我不知道为什么.
这是代码的简化版本;
function sendRequest(someargums) {
/* some code */
var the_variable;
/* some code */
request.onreadystatechange =
//here's that other function
function() {
if (request.readyState == 4) {
switch (request.status) {
case 200:
//here the variable should be changed
the_variable = request.responseXML;
/* a lot of code */
//somewhere here the function closes
}
return the_variable;
}
var data = sendRequest(someargums); //and trying to read the data I get the undefined value
解决方法:
AJAX请求是异步的.您的sendRuest函数正在被执行,正在进行AJAX请求,但它是异步发生的;所以在执行AJAX请求(以及你的onreadystatechange处理程序)之前执行sendRuest的剩余部分,因此返回时未定义the_variable.
实际上,您的代码的工作方式如下:
function sendRuest(someargums) {
/* some code */
var the_variable;
/* some code */
return the_variable;
}
var data = sendRequest(someargums);
然后一段时间后,您的AJAX请求正在完成;但现在已经太晚了
你需要使用一个叫做回调的东西:
你以前可能有过的地方
function () {
var theResult = sendRuest(args);
// do something;
}
你应该做:
function () {
sendRuest(args, function (theResult) {
// do something
});
};
并修改sendRuest,如下所示:
function sendRuest(someargums, callback) {
/* some code */
//here's that other function
request.onreadystatechange =
function() {
if (request.readyState == 4) {
switch (request.status) {
case 200:
callback(request.responseXML);
/* a lot of code */
//somewhere here the function closes
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。