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

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

问题描述

我使用原型来做我的 AJAX 开发,我使用这样的代码:

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?

推荐答案

请记住,在 someFunction 完成工作后很长一段时间内都会调用 onComplete.您需要做的是将回调函数作为参数传递给 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天全站免登陆