Web 服务器无法将未经请求的数据推送到客户端;他们遵守请求-响应周期。另一种方法是在复杂性显着增加的情况下使用消息队列。
来自客户端的轮询还不错; Web 服务器擅长处理许多短请求,2 或 3 秒的轮询间隔应该足够快。
这是我喜欢使用的一种轮询方法。它在再次轮询之前异步等待响应返回(需要 jQuery):
function poll(url, task, progressBar, resultsCallback,
timeoutMillis, pollIntervalMillis) {
$.ajax({
url: url,
type: 'GET',
dataType: 'json',
timeout: timeoutMillis,
data: 'action=poll&task='+task,
success: (function(response, status, xhr) {
if ('progress' in response) {
// update the UI with the progress
progressBar.setValue(response.progress);
}
if ('status' in response) {
if (response.status == 'pending') {
// task is not finished, continue polling
setTimeout((function() {
poll(url, task, progressBar, resultsCallback,
timeoutMillis, pollIntervalMillis);
}), pollIntervalMillis);
}
else {
// task completed
if (response.status == 'cancelled') {
progressBar.setColor('red');
progressBar.setText("Task '"+task+"' was cancelled");
}
else {
progressBar.setColor('green');
progressBar.setText("Task '"+task+"' complete");
}
// GET the results
$.ajax({
url: url,
type: 'GET',
timeout: timeoutMillis,
data: 'action=results&task='+task,
success: (function(response, status, xhr) {
resultsCallback(response, status, xhr);
}),
error: error
});
}
}
}),
error: error
});
function error(xhr, status, err) {
alert('Failure to communicate with server: ' + status + ', ' + err);
}
}
并且您的服务器端代码应该使用以下内容响应民意调查:
{"progress" : 42, "status" : "pending"}