好处:1.和AJAX轮询比起来 节省资源,并且延迟小, 2.和webSocket比起来,适用的场景比较广泛。

1.先建立一个Asp.net MVC的空项目

添加一个控制器  (同样的代码在Asp.net WebForm中也是可以使用的)

复制代码 代码如下:
public class CometController : Controller
    {
        public ActionResult Test()
        {
            Response.Buffer = false;
            while (true)
            {
                Response.Write(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss FFF") + "|");
                Thread.Sleep(500);
            }
            //跑不到这里的
            return Content("");
        }
    }
}

2.再兴建一个控制器和View 用于显示HTML

复制代码 代码如下:
public class HomeController : Controller
    {
        //
        // GET: /Home/

        public ActionResult Index()
        {
            return View();
        }

    }

View的代码比较重要

复制代码 代码如下:
@{
    Layout = null;
}
<!DOCTYPE html>
<html>
<head>
    <title>Index</title>
    <script type="text/javascript" src="/UploadFiles/2021-04-02/jquery-1.7.1.min.js">    <script language="javascript">
        var req = false;
        var lastDelimiterPosition = -1;

        $(document).ready(function () {
            getData();
        });

        function getData() {
            loadXMLDoc("/Comet/Test");
        }

        //新建一个XHR
function createRequest() {
            if (window.XMLHttpRequest && !(window.ActiveXObject)) {
                try {
                    req = new XMLHttpRequest();
                } catch (e) {
                    req = false;
                }        // branch for IE/Windows ActiveX version  
            } else if (window.ActiveXObject) {
                try { req = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) {
                    try {
                        req = new ActiveXObject("Microsoft.XMLHTTP");
                    } catch (e) {
                        req = false;
                    }
                }
            }
        }

        //发起请求
function loadXMLDoc(url) {
            try {
                if (req) {
                    req.abort();
                    req = false;
                }
                createRequest();
                if (req) {
                    req.onreadystatechange = processReqChange;
                    req.open("GET", url, true);
                    req.send("");
                } else {
                    alert('unable to create request');
                }
            } catch (e) { alert(e.message); }
        }

        //检查状态
function processReqChange() {
            if (req.readyState == 3) {
                try {
                    ProcessInput(req.responseText);
                    if (req.responseText.length > 3000) {
                        lastDelimiterPosition = -1; getData();
                    }
                }
                catch (e) {
                    alert(e.message);
                }
            }
        }


        //拆分字符串
function ProcessInput(input) {
            var text = input;
            var nextDelimiter = text.indexOf('|', lastDelimiterPosition + 1);
            if (nextDelimiter != -1) {
                var timeStamp = text.substring(nextDelimiter + 1);
                if (timeStamp.length > 0) {
                    lastDelimiterPosition = nextDelimiter;
                    ProcessTime(timeStamp);
                }
            }
        }

        //输出 或者触发什么事件
function ProcessTime(time) {
            document.getElementById('div1').innerHTML = time;
        }
    </script>
</head>
<body>
    <div>
        <div id="div1">
        </div>
        <div id="div2">
        </div>
    </div>
</body>
</html>

3.最终效果为:

页面上显示一个时间,每隔半秒钟更新一次

当然,拿到内容以后,其实你想做什么就做什么。。。更新DOM也好,执行js也好, (还好有eval这个方法~~)

4.这个例子只是基于异步Javascript的一个实现,

实际上还可以通过<iframe> 和 <script>这两个标签做实现,特别是script标签可以访问和执行跨域的javascript

广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!