参见英文答案 >
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); });