加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

如何返回AJAX响应文本?

发布时间:2020-12-16 03:18:08 所属栏目:百科 来源:网络整理
导读:参见英文答案 How do I return the response from an asynchronous call?16个答案我使用原型来做我的AJAX开发,我使用的代码如下: somefunction: function(){ var result = ""; myAjax = new Ajax.Request(postUrl,{ method: 'post',postBody: postData,con
参见英文答案 > How do I return the response from an asynchronous call?16个答案我使用原型来做我的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,onComplete: function(transport){
            if (200 == transport.status) {
                result = transport.responseText;
                return result;
            }
        }
    });

}

但它没有工作也。如何获得responseText的其他方法使用?

记住onComplete是在someFunction完成工作后很久才调用的。你需要做的是将回调函数作为参数传递给some函数。当进程完成工作时(即onComplete),将调用此函数:
somefunction: function(callback){
    var result = "";
    myAjax = new Ajax.Request(postUrl,onComplete: function(transport){
            if (200 == transport.status) {
                result = transport.responseText;
                callback(result);
            }
        }
    });

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读