港囧音乐,国足12强赛赛程表,九天逍遥
好处:1.和ajax轮询比起来 节省资源,并且延迟小, 2.和websocket比起来,适用的场景比较广泛。
1.先建立一个asp.net mvc的空项目
添加一个控制器 (同样的代码在asp.net webform中也是可以使用的)
2.再兴建一个控制器和view 用于显示html
public actionresult index()
{
return view();
}
}
view的代码比较重要
$(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
如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复
asp.net搭建博客,使用BlogEngine.NET+MySql搭建博客
网友评论