jQuery+PHP realizes dynamic digital display effects

  • 2020-05-16 06:21:07
  • OfStack

HTML

This example assumes that dynamic display (no need to refresh the whole page, only partial refresh of dynamic number) is needed on the page, which is commonly used on some statistical platforms. In the HTML page, simply define the following structure:


<div class="count"> Current online: <span id="number"></span></div>

jQuery

First, we need to define an animation process. jQuery's animate() function is used to transform from one number to another. The following magic_number() custom function integrates the code as follows:


function magic_number(value) {
    var num = $("#number");
    num.animate({count: value}, {
        duration: 500,
        step: function() {
            num.text(String(parseInt(this.count)));
        }
    });
};

The update() function then USES jQuery's $.getJSON () to send an ajax request to number.php, and after getting an PHP response, calls magic_number() to show the latest number. To see better results, we use setInterval() to set the interval time between code executions.


function update() {
    $.getJSON("number.php?jsonp=?", function(data) {
        magic_number(data.n);
    });
};
setInterval(update, 5000); //5 Seconds to perform 1 time
update();

PHP

In a real project, we would use PHP to get the latest data in the database and then return it to the front end via PHP. For a better demonstration, this example USES random Numbers and returns the code to the front end js, number.php in json format:


$total_data = array(
    'n' => rand(0,999)
);    
echo $_GET['jsonp'].'('. json_encode($total_data) . ')';  

The above is the article to share jQuery+PHP dynamic digital display effect code, I hope you can like it.


Related articles: