我在python中創建了我自己的聊天網絡服務器,並且想知道AJAX每秒鐘都會調用服務器(下面的JS)。我可以修改我的服務器,以便在更新chat.html文件時將其推送給所有客戶端。有沒有一種方法使用JavaScript來讓它監聽接收的數據而不是輪詢?AJAX監聽器而不是輪詢?
<script>
// Request the AJAX update the chat window every second
setInterval(function(){loadChat()},1000);
function loadChat()
{
var xmlhttp;
if (window.XMLHttpRequest)
{
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("chatWindow").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","chat.html",true);
xmlhttp.send(null);
}
}
</script>
因爲WebSockets的不做輪詢和他們是一個可能的解決方案。還有其他的東西列在我的答案。 – icktoofay 2013-03-02 03:58:49
酷,所以它是一個JS庫,試圖給當前不支持它的瀏覽器提供HTML5 websocket功能。 – LF4 2013-03-02 04:00:22
對,我建議使用SockJS,因爲它使用了這些技術的組合。 – 2013-03-02 04:00:32