日常生活中,有很多需要数据的实时更新,比如群聊信息的实时更新,还有投票系统的实时刷新等
实现的方式有很多种,比如轮询、长轮询、websocket
轮询
轮询是通过设置页面的刷新频率(设置多长时间自动刷新一次页面)来实现的。
使用轮询的机制模拟投票系统的实时刷新
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Title</title> </head> <body> <ul> {% for k,v in dic.items() %} <li style="cursor:pointer" ondblclick="ticket('{{k}}')">{{v.name}}:{{v.count}}</li> {% endfor %} </ul> </body> <script src="/static/jquery-3.3.1.js"></script> <script> function ticket(nid){ $.ajax({ url:'/ticket', type:'post', data:{nid:nid}, success:function (arg) { } }) } setInterval(function () { window.location.reload(); },2000); </script> </html>