【问题标题】:How to return AJAX response Text? [duplicate]如何返回 AJAX 响应文本? [复制]
【发布时间】:2009-08-04 03:55:28
【问题描述】:

我使用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;
}

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

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 以供其他方法使用?

【问题讨论】:

    标签: ajax prototypejs javascript


    【解决方案1】:

    请记住,在 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);
    });
    

    【讨论】:

    • 您的回答很棒,更实用/oop 风格,而且非常非常棒。然而,[someone]-s 的回答很中肯:asynchronous: false 更容易,并且更容易完成问题作者想要的(但您的解决方案更具可扩展性和灵活性)。
    • asynchronous: false 将停止浏览器,直到收到响应。如果网络连接很慢,所以连接服务器需要几秒钟,那么整个浏览器可能会冻结几秒钟,并且不会响应用户输入。这不是很好的可用性。它可能更简单,但性能不佳,因此永远不应使用 asynchronous:false
    • 对不起,我之前没有真正使用过异步。你是对的,所以这和function ajaxLoader(){var fAjaxLoaded = false;$.ajax(...,success: function(){fAjaxLoaded = true;}); while(fAjaxLoaded);return ...}基本相同
    • 这和停止javascript线程一样,不可用。根据我的经验,回调工作得更好,代码更有条理(这样,我的代码通常包含许多函数和 5-6 个迷你调用:))。
    【解决方案2】:

    如何在您的代码中添加“异步:false”?就我而言,它运作良好:)

    【讨论】:

    • 这违背了ajax的目的吧?
    • 这很糟糕,因为使用同步请求,您会阻止浏览器中的所有 JS 执行,直到请求返回。
    • 达不到目的,但可以节省您的时间。
    猜你喜欢
    • 2013-06-17
    • 1970-01-01
    • 1970-01-01
    • 2011-08-22
    • 1970-01-01
    • 2015-11-28
    • 2019-05-26
    • 2015-05-04
    • 2016-12-14
    相关资源
    最近更新 更多