Php 无需重新加载页面即可更改的动态计数器
我有一个运行php和mySQL数据库的网站。对于每个访问该站点的访问者,我都会将用户会话(过去5分钟)记录在一个单独的表中Php 无需重新加载页面即可更改的动态计数器,php,javascript,mysql,ajax,jquery,Php,Javascript,Mysql,Ajax,Jquery,我有一个运行php和mySQL数据库的网站。对于每个访问该站点的访问者,我都会将用户会话(过去5分钟)记录在一个单独的表中 如何在页面上创建一个动态计数器,在不重新加载页面的情况下更改活动会话的数量,即,如果我在网站上,而其他15个人进入,计数器将自动更改,而不需要我重新加载页面。在最基本的情况下,您可以通过AJAX轮询服务器脚本。该PHP脚本将响应一些所需的信息,如在线用户编号、那些用户名等。因此示例javascript部分: // Poll the server each 60 second
如何在页面上创建一个动态计数器,在不重新加载页面的情况下更改活动会话的数量,即,如果我在网站上,而其他15个人进入,计数器将自动更改,而不需要我重新加载页面。在最基本的情况下,您可以通过AJAX轮询服务器脚本。该PHP脚本将响应一些所需的信息,如在线用户编号、那些用户名等。因此示例javascript部分:
// 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\u 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
)));
在最基本的情况下,您可以通过AJAX轮询服务器脚本。该PHP脚本将响应一些所需的信息,如在线用户编号、那些用户名等。因此示例javascript部分:
// 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\u 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
)));
非常感谢。我用您提供的代码尝试了这一点,但没有输出任何内容。我得仔细研究一下。只有一个问题。。我不需要“呼应”计数就能显示出来?谢谢我提供的代码很好用。仔细看看。当然,您需要php脚本作为响应输出一些内容<代码>回显
,模具
,打印
,等等。如果您只需要一个数字,只需更改为回显25
或die(25)
。您也可以将间隔更改为小于1分钟,可能这就是您没有输出的原因,因为必须先过1分钟。非常感谢。我用您提供的代码尝试了这一点,但没有输出任何内容。我得仔细研究一下。只有一个问题。。我不需要“呼应”计数就能显示出来?谢谢我提供的代码很好用。仔细看看。当然,您需要php脚本作为响应输出一些内容<代码>回显
,模具
,打印
,等等。如果您只需要一个数字,只需更改为回显25
或die(25)
。您还可以将间隔更改为小于1分钟,这可能就是您没有输出的原因,因为必须先通过1分钟。