English 中文(简体)
AJAX:等待响应中?
原标题:AJAX: Waiting for response?

我使用全局变量来传递从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

但那只会让我的浏览器无响应。

我不太确定是否应该从回调函数中调用所需的函数,因为我正在尝试实现模型-视图-控制器。从模型中调用控制器/视图功能似乎会破坏模式。

最佳回答

这里最好的做法是将您目前在loadUsernameInfo中的代码放在 AJAX 调用本身的回调中,而不是依赖全局变量。这样,当您的响应返回时,执行回调的回调,而不仅仅是设置您的 window.response 变量,将实际更新您的 UI 并执行任何其他相关任务。

做同样的事情的另一种方法是从现有的回调函数中调用loadUsernameInfo,像这样:

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

希望有所帮助!

问题回答

您的XMLHttpRequest应当利用即刻的改变活动,例如:

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

}

其中,callback()是您想要调用的函数。readyState为4意味着内容已经加载完成。两个状态条目是为了确保URL没有出现错误。

function userObjFromJSON() {
if (this.readyState == 4) {
    var json = eval( (  + this.responseText +  ) );
    window.response = json;
// why dont you call needed function here ?
Sorry, I am unable to translate without the text. Please provide the text you want translated.
else {
    indicateLoading();
Sorry, I am unable to translate without the text. Please provide the text you want translated.

Sorry, I am unable to translate without the text. Please provide the text you want translated.

当设置window.response时,为什么不调用所有必要的函数? (dāng shèzhì window.response shí, wèishéme bù diào yòng suǒyǒu bìyào de hánshù?)

最糟糕的情况下,您可以使用window.setTimeout等待ajax响应,但最好的方法是使用事件。





相关问题
selected text in iframe

How to get a selected text inside a iframe. I my page i m having a iframe which is editable true. So how can i get the selected text in that iframe.

How to fire event handlers on the link using javascript

I would like to click a link in my page using javascript. I would like to Fire event handlers on the link without navigating. How can this be done? This has to work both in firefox and Internet ...

How to Add script codes before the </body> tag ASP.NET

Heres the problem, In Masterpage, the google analytics code were pasted before the end of body tag. In ASPX page, I need to generate a script (google addItem tracker) using codebehind ClientScript ...

Clipboard access using Javascript - sans Flash?

Is there a reliable way to access the client machine s clipboard using Javascript? I continue to run into permissions issues when attempting to do this. How does Google Docs do this? Do they use ...

javascript debugging question

I have a large javascript which I didn t write but I need to use it and I m slowely going trough it trying to figure out what does it do and how, I m using alert to print out what it does but now I ...

Parsing date like twitter

I ve made a little forum and I want parse the date on newest posts like twitter, you know "posted 40 minutes ago ","posted 1 hour ago"... What s the best way ? Thanx.

热门标签