javascript利用xhr对象实现http流的comet轮循,主要是利用readyState等于3的特点

//此文件 为前端获取http流

html 复制代码
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" lang="UTF-8"></html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
        <title>拖动元素到另外一个元素当中</title>
       <script type="text/javascript" src="common.js"></script>
       <style type="text/css">
            #container
            {
                border:1px solid red;
                width: 300px;
                height: 300px;
            }
            #getmsg 
            {
                border: 1px solid blue;
                width: 200px;
                height: 200px;
                margin-top: 20px;
            }
        </style>
    </head>
    <body>
      
        <script type="text/javascript">
          


            var xhr=new createXHR();
            xhr.onreadystatechange=function(){
                if(xhr.readyState===3 && xhr.status===200)
                {
                    var received=0;
                    var result=xhr.responseText.substring(received);
                    received+=result.length;
                    process(result);
                }else if(xhr.readyState===4)
                {
                    console.log(xhr.responseText);
                }
            };
            xhr.open("get","data.php",true);
            xhr.send();
            function process(result)
            {
                
                var arr=result.split("\t\n");
                arr.pop();
                
                
                for(var i=0,len=arr.length;i<len;i++)
                {
                  document.write(JSON.parse(arr[i]).text+"<br/>");

                }
               // console.log(objs);
               
            }
            
        </script>
    </body>
</html>

//此文件为后端data.php

php 复制代码
<?php
header('Content-type:application/json;charset=utf-8');
header("Cache-Control:max-age=0");//设置无缓存
$i=0;
while($i<10)
{
    $i++;
    $result=array('success'=>'ok','text'=>'测试文本');
    echo json_encode($result,JSON_UNESCAPED_UNICODE);//设置汉字不进行轮换
  	//要输出linux格式的空格,避免成一坨不好分格
  	echo "\t\n";
    
    sleep(1);
    /*
    $radom=rand(1,999);
    echo $radom;
   */
   //输出缓存,必须和flush()一起使用
    ob_flush();
    flush();//刷新缓存
     
}
?>
相关推荐
jerryinwuhan2 小时前
基于各城市站点流量的复合功能比较
开发语言·php
迈巴赫车主2 小时前
Java基础:list、set、map一遍过
java·开发语言
ZC跨境爬虫3 小时前
跟着MDN学HTML_day_48:(Node接口)
前端·javascript·ui·html·音视频
南 阳3 小时前
Python从入门到精通day66
开发语言·python
十八旬4 小时前
快速安装ClaudeCode完整指南
开发语言·windows·python·claude
前进的李工5 小时前
EXPLAIN输出格式全解析:JSON、TREE与可视化
开发语言·数据库·mysql·性能优化·explain
Byron Loong5 小时前
【c++】为什么有了dll和.h,还需要包含lib
java·开发语言·c++
kyriewen5 小时前
半夜三点线上崩了,AI替我背了锅——用AI排错,五分钟定位三年老bug
前端·javascript·ai编程
独隅6 小时前
CodeX + Visual Studio Code 联动的全面指南
开发语言·php
坚果派·白晓明6 小时前
【鸿蒙PC三方库移植适配框架解读系列】第一篇:Lycium C/C++ 三方库适配 — 概述与环境配置
c语言·开发语言·c++·harmonyos·开源鸿蒙·三方库·c/c++三方库