The Jq data list is dynamically updated and supports Ajax Dynamic refresh. The following small series will show you how to use jQuery to display dynamic numbers. For more information, see How to dynamically display data in some applications, such as the number of online users and the total amount of transactions, the current exchange rate, etc. the front-end page needs to be refreshed in real time to obtain the latest data. This article introduces how to use jQuery to display dynamic numbers.
View demo download source code
HTML code
This example assumes that the current number of online users needs to be dynamically displayed on the page (the entire page does not need to be refreshed, but dynamic numbers are only refreshed locally), which is usually applied on some statistical platforms. On the HTML page, you only need to define the following structure:
Currently online:
JQuery code:
First, we need to define an animation process, and use the animate () function of jQuery 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))); } }); };
Then, the update () function uses jQuery's $. getJSON () to send an ajax request to number. php in the background. after obtaining the corresponding PHP request, it calls magic_number () to display the latest number.
To see better results, we use setInterval () to set the interval between code execution.
Function update () {$. getJSON ("number. php? Jsonp =? ", Function (data) {magic_number (data. n) ;}; setInterval (update, 5000); // execute an update () in 5 seconds; PHP
In actual projects, we will use PHP to obtain the latest data in the database and then return it to the front-end through PHP. For better demonstration, this example uses random numbers and returns them to the front-end js in json format. the number. php code is as follows:
$total_data = array( 'n' => rand(0,999) ); echo $_GET['jsonp'].'('. json_encode($total_data) . ')';