我使用原型进行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?
答案 0 :(得分: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);
});
答案 1 :(得分:3)
如何在代码中添加“asynchronous:false”?就我而言,它运作良好:)