使用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
本文介绍了一个使用XMLHttpRequest.js来提供跨浏览器兼容的XMLHttpRequest对象实现,修复了各浏览器原生实现的差异。同时,展示了如何在PHP中实现长轮询,通过output.php的例子,详细解释了关闭输出缓冲、禁用压缩和实时输出的设置。在JavaScript端,利用AJAX进行长轮询并与PHP服务器进行交互,输出数据流并监控请求状态。

被折叠的 条评论
为什么被折叠?



