使用XMLHttpRequest.js交付XMLHttpRequest 1.0对象的不引人注目的标准兼容(W3C)跨浏览器实现
修复所有浏览器在其原生XMLHttpRequest对象实现中观察到的怪癖。
启用XMLHttpRequest对象活动的透明日志记录。
要在PHP中使用长轮询:
output.php:<?php
header('Content-type: application/octet-stream');// Turn off output bufferingini_set('output_buffering', 'off');// Turn off PHP output compressionini_set('zlib.output_compression', false);// Implicitly flush the buffer(s)ini_set('implicit_flush', true);ob_implicit_flush(true);// Clear, and turn off output bufferingwhile (ob_get_level() > 0) {
// Get the curent level
$level = ob_get_level();
// End the buffering
ob_end_clean();
// If the current level has not changed, abort
if (ob_get_level() == $level) break;}// Disable apache output buffering/compressionif (function_exists('apache_setenv')) {
apache_setenv('no-gzip', '1');
apache_setenv('dont-vary', '1');}// Count to 20, outputting each secondfor ($i = 0;$i
echo $i.str_repeat(' ', 2048).PHP_EOL;
flush();
sleep(1);}
php:$(function() {
var xhr = new XMLHttpRequest();
xhr.open('GET', '/longpoll/', true);
xhr.send(null);
var timer;
timer = window.setInterval(function() {
if (xhr.readyState == XMLHttpRequest.DONE) {
window.clearTimeout(timer);
$('body').append('done
');
}
$('body').append('state: ' + xhr.readyState + '
');
console.log(xhr.responseText);
$('body').append('data: ' + xhr.responseText + '
');
}, 1000);});
这应该是产出:state: 3data: 0state: 3data: 0 1state: 3data: 0 1 2state: 3data: 0 1 2 3state: 3data: 0 1 2 3 4.........state: 3data: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17state: 3data: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18state: 3data: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19donestate: 4data: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
对于IE,您需要查看XDomainRequest