像Twitter这样的实时更新

Pra*_*bhu 1 .net c# asp.net asp.net-mvc jquery

你如何实现像Twitter这样的实时更新("自你开始搜索以来,还有423条推文")?我需要至少每10秒刷新一次页面.我正在使用ASP.NET MVC和jquery.

Dar*_*rov 5

您可以使用setInterval javascript函数,该函数允许您使用AJAX定期轮询服务器以获取更新:

window.setInterval(function() {
    // This will be executed each 5s
    // TODO: query your server for updates probably using AJAX
    // example with jquery:
    $.getJSON('/arethereanyupdates', function(data) {
        if (data.isupdates) {
            alert('yeap there are updates');
        }
    });
}, 5000);
Run Code Online (Sandbox Code Playgroud)

在HTML5中还有一种称为WebSockets的推送技术,它允许服务器通知客户端更新,但当然你需要一个HTML5兼容的浏览器,现在不难找到并且符合WebSocket API的服务器.