我需要每 10 秒发出一次 ajax 请求并在客户端更新数据。
所以,我在 onModuleLoad() 中尝试了这种方式:
while (true) {
try {
someService.initTable(new AsyncCallback<SomeObject>() {
@Override
public void onFailure(Throwable caught) {
}
@Override
public void onSuccess(SomeObject result) {
initData(numbersTable, result);
}
});
} catch (Exception e) {
}
}
但它进入无限循环。
我想要得到这样的东西
(function worker() {
$.ajax({
url: 'ajax/test.html',
success: function(data) {
$('.result').html(data);
},
complete: function() {
// Schedule the next request when the current one's complete
setTimeout(worker, 5000);
}
});
})();
最佳答案
gwt 中的异步调用立即执行,并“稍后”返回。在您的代码中, while 循环不等待任何东西,因此您每秒调用 initTable() 很多次,因此是无限循环。
只需创建一个每 10 秒执行一次的计时器即可。
final Timer timer = new Timer() {
@Override
public void run() {
try {
someService.initTable(new AsyncCallback<SomeObject>() {
@Override
public void onFailure(Throwable caught) {
}
@Override
public void onSuccess(SomeObject result) {
initData(numbersTable, result);
}
});
} catch (Exception e) {
}
}
};
timer.scheduleRepeating(10000);
关于java - 如何在 GWT 中循环 AsyncAjaxRequest?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33885220/