1 回答

TA貢獻(xiàn)1812條經(jīng)驗(yàn) 獲得超5個(gè)贊
問(wèn)題在于.load()
方法的使用,該方法可能有用,但不適用于本例。.load()
在其內(nèi)部,$.ajax()
您可以使用 jQuery 向服務(wù)器發(fā)出請(qǐng)求。使用它來(lái)訪問(wèn)服務(wù)器隨每個(gè)請(qǐng)求返回的玩家計(jì)數(shù)值。
將代碼分為兩個(gè)函數(shù),一個(gè)用于獲取玩家計(jì)數(shù),另一個(gè)用于使用動(dòng)畫更新玩家計(jì)數(shù)。每當(dāng)?shù)谝粋€(gè)函數(shù)下載了新的計(jì)數(shù)并且該計(jì)數(shù)與您已有的計(jì)數(shù)不同時(shí),請(qǐng)調(diào)用第二個(gè)函數(shù)進(jìn)行更新和動(dòng)畫處理。
<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 關(guān)注
- 245 瀏覽
添加回答
舉報(bào)