2010-02-22 127 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