我使用全局變量來繞過從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