一尘不染

JavaScript如何返回AJAX响应文本?

javascript

我使用原型进行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供其他方法使用?


阅读 413

收藏
2020-04-23

共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);
});
2020-04-23