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"}


