如何使用YAHOO.util.Connect.asyncRequest并返回结果? [英] How to use YAHOO.util.Connect.asyncRequest and return results?
问题描述
我正在使用YAHOO.util.Connect.asyncRequest从数据库中获取数据,这里是代码:
I'm using YAHOO.util.Connect.asyncRequest to get data from database, here is the code :
function getCountArticle(contentCurValue) {
var handleSuccess = function (res) {
var countPubmed = YAHOO.lang.JSON.parse(res.responseText);
var contentCountPubmed = countPubmed.totalArticleRecords;
alert(contentCountPubmed); //return 15 for example
};
var handleFailure = function () {
alert("Error connecting data : Bad pubmed query");
};
var callback =
{
success:handleSuccess,
failure:handleFailure,
timeout: 5000
};
var sURL = 'qct-list-article.html?term=' + contentCurValue + '&retstart=0' + '&retmax=1';
var request = YAHOO.util.Connect.asyncRequest('GET',sURL,callback);
}
我希望此函数返回:contentCurValue(例如:15),但是当我尝试使用这段代码时,我得到未定义:
I would like this function return : "contentCurValue" (eg:15), but when I try to use this code I get "undefined" :
var test = getCountArticle();
alert(test); // return undefined, should return 15
我的错误可能是由于异步查询,但我怎么能强制var test = getCountArticle(); 等待结果?
My error is probably due to asynchronous query, but how can I force "var test = getCountArticle();" to wait for results ?
推荐答案
由于调用本质上是异步的,而不是试图等待对于响应,最好指定一个回调函数来执行数据。您可以像这样修改您的方法:
Since the call is by nature asynchronous, rather than try to wait for the response, you would be better off specifying a callback function to execute with the data. You could modify your method like this:
function getCountArticle(contentCurValue, callback) {
var handleSuccess = function (res) {
var countPubmed = YAHOO.lang.JSON.parse(res.responseText);
var contentCountPubmed = countPubmed.totalArticleRecords;
callback(contentCountPubmed); //return 15 for example
};
// ...
}
然后你的主叫代码是:
then your calling code would be:
getCountArticle("contentCurValue", function(test) {
alert(test);
});
使用从AJAX查询返回的值的任何进一步执行都将在您的回调方法中进行。
Any further execution using the value returned from your AJAX query would proceed inside of your callback method.
这个SO帖子基本上是同一个问题,但不是YUI特定的:在调用ajax时在javascript中获取未定义
This SO post is essentially the same problem, but not YUI specific: Getting undefined in javascript when calling ajax
这篇关于如何使用YAHOO.util.Connect.asyncRequest并返回结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!