没有页面重新加载而更改的动态计数器

时间:2012-01-18 20:44:33

标签: php javascript mysql ajax jquery

我有一个运行带有mySQL数据库的php的网站。对于我访问该网站的每位访问者,我将用户会话(从过去5分钟)记录在一个单独的表中。

如何在页面上创建一个动态计数器,可以在不重新加载页面的情况下更改活动会话的数量,即如果我在网站上,并且其他15个人进入计数器将自动更改,而不会重新加载页面。

1 个答案:

答案 0 :(得分:1)

在最基本的情况下,您可以通过AJAX轮询服务器脚本。 PHP脚本会响应一些所需的信息,如在线用户号,那些用户名等。例如javascript part:

// Poll the server each 60 seconds
window.setInterval(function() {
    $.getJSON('/online_users.php', function(data) {
        // Here the data JSON returned by a PHP script
        // e.g. data.count - count of sessions online
        // data.users - could be array of user objects, etc
        $('#counter').text(data.count); // Update some DOM element with new number
    });
}, 60000);

服务器端online_users.php

<?php

// connect to DB, perform all necessary operations
// output needed info in JSON format

$users = array(
    array('username' => 'Tomas', 'id' => 234),
    array('username' => 'Jassy', 'id' => 42)
);
$count = count($users);

header('Content-type: application/json');
die(json_encode(array(
    'count' => $count,
    'users' => $users
)));
相关问题