亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

HTML AJAX 實時更新 PHP 變量,使用 ajax 進行計數動畫

HTML AJAX 實時更新 PHP 變量,使用 ajax 進行計數動畫

PHP
慕村9548890 2023-11-03 15:53:54
我正在嘗試制作每秒更新一次的實時變量,但當我在那里添加計數函數時,我可以看到 0 1 秒,之后該變量顯示沒有動畫。我的目標是使變量在第一次加載頁面時從 0 計數到“var.value”,例如18,如果變量更改為例如20,那么將會有 count ani。從18到20。我實際上不知道如何實現它,因為我無法獲取先前的變量,因為它存儲在global_users.php中索引.php<script>$(document).ready(function() {    $("#players").load("global_users.php")    setInterval(function () {        $("#players").load("global_users.php")    }, 1000);});</script><span class="Count" id="players"></span><script>    $('.Count').each(function () {        $(this).prop('Counter',0).animate({            Counter: $(this).text()        }, {            duration: 1000,            easing: 'swing',            step: function (now) {                $(this).text(Math.ceil(now));            }        });    });</script>全局用戶.php<?phpinclude("php/server.php");echo $total_online = $serverInfo['Players'];?>
查看完整描述

1 回答

?
慕雪6442864

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);


});


查看完整回答
反對 回復 2023-11-03
  • 1 回答
  • 0 關注
  • 209 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號