1 回答
TA贡献1812条经验 获得超5个赞
问题在于.load()
方法的使用,该方法可能有用,但不适用于本例。.load()
在其内部,$.ajax()
您可以使用 jQuery 向服务器发出请求。使用它来访问服务器随每个请求返回的玩家计数值。
将代码分为两个函数,一个用于获取玩家计数,另一个用于使用动画更新玩家计数。每当第一个函数下载了新的计数并且该计数与您已有的计数不同时,请调用第二个函数进行更新和动画处理。
<span class="count" id="players"></span>
$(document).ready(function() {
// Set starting count.
let count = 0;
const $players = $('#players');
/**
* Updates the player count with an animation and
* saves the new player count.
*/
function updatePlayerCount(newCount) {
$({
counter: count // Starting value, which is the last known count value.
}).animate({
counter: newCount // Value to animate to, which is the new count value.
}, {
duration: 1000,
easing: 'swing',
step: function() {
$players.text(Math.ceil(this.counter));
},
complete: function() {
count = newCount; // Update the count value after the animation to compare it later again.
}
});
}
/**
* Gets the count value from the server and
* passes it to the updatePlayerCount function
* if the count has been changed.
*/
function getPlayerCount() {
$.ajax({
url: 'global_users.php',
method: 'GET'
}).done(function(newCount) {
newCount = Number(newCount); // Makes sure that the value is a number.
if (count !== newCount) {
updatePlayerCount(newCount); // newCount is a different value than count, so updatePlayerCount is called.
}
});
}
// Execute getPlayerCount every 5 seconds.
setInterval(getPlayerCount, 5000);
});
- 1 回答
- 0 关注
- 139 浏览
添加回答
举报