我不清楚以下虚拟代码的返回值:
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调用完成后再转到下一行.因此,它总是返回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
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。