如何返回Ajax响应文本? [英] How to return AJAX response Text?

查看:240
本文介绍了如何返回Ajax响应文本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用原型做我的AJAX开发,我用的是code是这样的:

I use prototype to do my AJAX development, and I use the code like this:

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;
}

和我发现,结果是一个空字符串。所以,我想这样的:

And I find that the "result" is an empty string. So, I tried this:

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其他的方法来使用?

But it didn't work also. How can I get the responseText for other method to use?

推荐答案

记住的onComplete被称为someFunction完成工作后不久。什么,你需要做的是传递一个回调函数来somefunction作为参数。当这个过程完成工作,此功能将被调用(即的onComplete):

remember that onComplete is called long after the someFunction is done working. What you need to do is pass a callback function to the somefunction as a parameter. This function will be called when the process is done working (ie, 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);
});

这篇关于如何返回Ajax响应文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆