HTML5 引入了一个非常有趣的概念,称为服务器发送事件,其中服务器可以动态连接到客户端并发送数据。
例如:
var source = new EventSource("demo_sse.asp");
source.onmessage = function(event) {
document.getElementById("result").innerHTML = event.data + "<br>";
};
在服务器端你可以写,
<%
Response.ContentType = "text/event-stream"
Response.Expires = -1
<!--Writing "data:" is important-->
Response.Write("data: The server time is: " & now())
Response.Flush()
%>
但是,某些旧浏览器可能不支持此功能。
完成此任务的另一种方法是使用 Ajax 调用,
function checkNewMessages(totalMessages){
return $.ajax({
url: 'demo.asp',
type: 'GET',
cache: false,
data: {
totalMessages: totalMessage;
}
});
}
checkNewMessages(totalMessages).success(function (data) {
// display the data wherever you want
});
//Checking for new messages every 5 seconds
setInterval(checkNewMessages(totalMessages,5000));
无论您Write()
在服务器端写入什么内容,都将显示在此处。现在要不断检查新消息,您可以在以下帮助下调用上述 ajax 函数setInterval()