为了账号安全,请及时绑定邮箱和手机立即绑定

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 关注
  • 74 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信