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();//刷新缓存
     
}
?>
相关推荐
Ulyanov1 小时前
Python实现6-DOF刚体仿真器(下)——环境扰动与控制闭环
开发语言·python·算法·系统仿真·雷达电子对抗·导引头
分布式存储与RustFS1 小时前
RustFS Beta.10 性能解读:PUT 全面反超 MinIO,Rust 重写对象存储成了?
开发语言·后端·rust
小小的木头人2 小时前
Python 批量解析 Excel 经纬度,调用高德地图 API 获取中文地址
开发语言·python·excel
Listen·Rain2 小时前
Vue3中组件间通信详解
前端·javascript·vue.js
Listen·Rain2 小时前
Vue3中customRef详解
前端·javascript·vue.js
nzz_1712142 小时前
PHP程序员转型AI岗位指南:核心技能、北京就业市场与转型路径分析
开发语言·人工智能·php
香芋芋圆2 小时前
国内常用坐标系全解析与WebGIS框架实战指南(Cesium/Mapbox/Leaflet避坑手册)
前端·javascript
sugar__salt3 小时前
Document 切割:RAG 知识库数据预处理实战
javascript·langchain·embedding·js·rag·cheerio
Risehuxyc3 小时前
C# 将doc转换为docx
开发语言·c#·xhtml
小粉粉hhh3 小时前
React(三)——Redux
前端·javascript·react.js