ajax zlib,jQuery递增地读取Ajax流吗?

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

使用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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值