Ajax 实现长轮询(long-polling)
长轮询是现在最为常用的方式,和流方式的区别就是服务器端在接到请求后挂起,有更新时返回连接即断掉,然后客户端再发起新的连接
<script language="javascript" type="text/javascript">
var updater = {
poll: function() {
$.ajax({ url: "Handler1.ashx",
type: "POST",
dataType: "text",
success: updater.onSuccess,
error: updater.onError
});
},
onSuccess: function(data, dataStatus) {
try {
$("p").append(data + "<br>");
}
catch (e) {
updater.onError();
return;
}
interval = window.setTimeout(updater.poll, 0);
},
onError: function() {
console.log("Poll error;");
}
};
updater.poll();
</script>