我使用全局变量来绕过从AJAX调用的响应:AJAX:等待回应?
window.response = null; // most recent response from XMLHttpRequest
// the callback function for XMLHttpRequest
function userObjFromJSON() {
if (this.readyState == 4) {
var json = eval('(' + this.responseText + ')');
window.response = json;
}
else {
indicateLoading();
}
}
// loads the info for this username on the page
function loadUsernameInfo(username) {
clearPage();
getUserInfo(username);
var profile = window.response; // most recent json response (what if it hasn't come in yet?)
window.response = null;
if (profile) {
indicateLoaded(username);
fillInProfileInfo(profile);
getTweets(username);
var tweets = window.response; // most recent json response (what if it hasn't come in yet?)
if (tweets) {
fillInTweets(tweets, MAX_TWEETS);
var mentions = mentionedUsers(tweets, MAX_TWEETS);
fillInMentioned(mentions);
}
else {
indicateUnavailableTweets();
}
}
else {
indicateInvalidUsername(username);
}
}
的问题是,由控制器功能要开始在填写信息时,AJAX调用并不总是还没回来。 (如果我在调试器中缓慢地逐步调试,它可以很好地工作。)我能做些什么来解决这个问题?
我想是这样的:
getUserInfo(username);
while (window.response == null); // infinite loop here
var profile = window.response; // most recent json response
但是,这只是让我的浏览器没有反应。
我很犹豫从回调调用所需的功能,因为我试图实现模型视图控制器。从模型调用控制器/视图函数会让它感觉到会破坏模式。
我想要做模型视图控制器,并把函数调用那里会违反。 – 2010-02-22 18:48:40