2010-02-22 99 views
2

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

但是,這只是讓我的瀏覽器沒有反應。

我很猶豫從回調調用所需的功能,因爲我試圖實現模型視圖控制器。從模型調用控制器/視圖函數會讓它感覺到會破壞模式。

回答

2

這裏的最佳做法是將當前在loadUsernameInfo中的代碼放入AJAX調用本身的回調中,而不是依賴全局變量。這樣,當你的響應回來時,執行的回調,而不是隻設置你的window.response變量,將實際上繼續並更新你的用戶界面,並執行任何其他相關的任務。

做同樣的事僅僅是調用loadUsernameInfo從現有的回調,像另一種方式:

// the callback function for XMLHttpRequest 
function userObjFromJSON() { 
    if (this.readyState == 4) { 
     var profile = eval('(' + this.responseText + ')'); 
     loadUsernameInfo(username, profile); 
    } 
    else { 
     indicateLoading(); 
    } 
} 

希望幫助!

0
function userObjFromJSON() { 
if (this.readyState == 4) { 
    var json = eval('(' + this.responseText + ')'); 
    window.response = json; 
// why dont you call needed function here ? 
} 
else { 
    indicateLoading(); 
} 

}

你爲什麼不叫所有需要的功能,當你設置window.response?

以最糟糕的方式,您可以使用window.setTimeout等待ajax回覆,但最好的方法是使用事件。

0

您的XMLHttpRequest應該使用onreadystatechange事件。例如:

var xmlHttp=new XMLHttpRequest(); 
xmlHttp.onreadystatechange=function(){ 
    if(xmlHttp.readyState!=4 || (xmlHttp.status!=200 && xmlHttp.status!=304))return; 
    callback(xmlHttp.responseText); 

} 

其中callback()是您希望它調用的函數。 4的readyState表示內容已完成加載。這兩個狀態條目是爲了確保網址沒有給出錯誤。

+0

我想要做模型視圖控制器,並把函數調用那裏會違反。 – 2010-02-22 18:48:40