如何返回AJAX响应文本?

41

我使用原型(prototype)来进行我的AJAX开发,代码看起来像这样:

somefunction: function(){
    var result = "";
    myAjax = new Ajax.Request(postUrl, {
        method: 'post',
        postBody: postData,
        contentType: 'application/x-www-form-urlencoded',
        onComplete: function(transport){
            if (200 == transport.status) {
                result = transport.responseText;
            }
        }
    });
    return result;
}

我发现“result”是一个空字符串。所以,我尝试了这个:

somefunction: function(){
    var result = "";
    myAjax = new Ajax.Request(postUrl, {
        method: 'post',
        postBody: postData,
        contentType: 'application/x-www-form-urlencoded',
        onComplete: function(transport){
            if (200 == transport.status) {
                result = transport.responseText;
                return result;
            }
        }
    });

}

但是它也没有起作用。我该如何获取responseText以便其他方法使用?

2个回答

29

记住,在 someFunction 完成工作很久之后才会调用 onComplete。您需要做的是将回调函数作为参数传递给 someFunction。当进程完成工作(即 onComplete)时,将调用此函数:

somefunction: function(callback){
    var result = "";
    myAjax = new Ajax.Request(postUrl, {
        method: 'post',
        postBody: postData,
        contentType: 'application/x-www-form-urlencoded',
        onComplete: function(transport){
            if (200 == transport.status) {
                result = transport.responseText;
                callback(result);
            }
        }
    });

}
somefunction(function(result){
  alert(result);
});

你的回答很棒,更加注重功能和面向对象编程风格,真的非常好。然而,[某人]的回答直戳问题要点:asynchronous: false 更容易实现并且能够轻松地完成问题作者想要的(但是你的解决方案更具可扩展性和灵活性)。 - Luka Ramishvili
1
asynchronous:false会导致浏览器一直等待直到接收到响应。如果网络连接缓慢,需要几秒钟才能连接到服务器,那么整个浏览器可能会冻结几秒钟,并且不会响应用户输入。这对用户体验来说非常糟糕。它可能更容易,但它的表现并不好,因此永远不应该使用asynchronous:false - Marius
不好意思,我之前实际上没有使用过异步。你是对的,所以这基本上与 function ajaxLoader(){var fAjaxLoaded = false;$.ajax(...,success: function(){fAjaxLoaded = true;}); while(fAjaxLoaded);return ...} 是一样的。 - Luka Ramishvili
这与停止JavaScript线程相同,无法使用。从我的经验来看,回调函数效果更好,可以产生更有组织的代码(这样,我的代码通常由许多函数和5-6个小型调用组成:))。 - Luka Ramishvili

3
你的代码中加入"asynchronous: false"怎么样?在我的情况下,这个方法很有效 :)

这不是违背了 Ajax 的初衷吗? - Arvind Sridharan
5
同步请求会阻塞浏览器中所有 JavaScript 的执行,直到请求返回结果,因此这是不好的。 - holographic-principle
2
打破了初衷,但救了你的一天。 - Sangram Nandkhile

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接