如何返回AJAX响应文本?

如何返回AJAX响应文本?,ajax,prototypejs,javascript,Ajax,Prototypejs,Javascript,我使用prototype进行AJAX开发,代码如下: somefunction: function(){ var result = ""; myAjax = new Ajax.Request(postUrl, { method: 'post', postBody: postData, contentType: 'application/x-www-form-urlencoded', onComplete: funct

我使用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?

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


在代码中添加“asynchronous:false”怎么样?在我的例子中,它工作得很好:)

你的答案很棒,更实用/oop风格,而且非常非常棒。但是,[someone]的答案是:异步:false更容易,并且更容易实现问题作者想要的功能(但您的解决方案更具可扩展性和灵活性)。异步:false将在收到响应之前停止浏览器。如果网络连接很慢,因此连接到服务器需要几秒钟,那么整个浏览器可能会冻结几秒钟,并且不会响应用户输入。这不是很好的可用性。它可能更简单,但性能不好,因此永远不应该使用
asynchronous:false
。您是对的,因此这基本上与
function ajaxLoader(){var fAjaxLoaded=false;$.ajax(…,success:function(){fAjaxLoaded=true;});while(fAjaxLoaded);return…}
这与停止javascript线程相同,不可用。根据我的经验,回调工作得更好,代码也更有条理(这样,我的代码通常由许多函数和5-6个小调用组成:)。这违背了ajax的目的,对吧?这很糟糕,因为对于同步请求,在请求返回之前,您正在阻止浏览器中的所有JS执行。这不符合目的,但节省了您的时间。
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);
});