如何返回AJAX响应文本?

DNB*_*ims 40 javascript ajax prototypejs

我用原型来做我的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;
}
Run Code Online (Sandbox Code Playgroud)

我发现"结果"是一个空字符串.所以,我试过这个:

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

}
Run Code Online (Sandbox Code Playgroud)

但它也没有用.如何获取其他方法的responseText?

Mar*_*ius 28

请记住,在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);
});
Run Code Online (Sandbox Code Playgroud)