We need to dynamically display data in some applications, such as the current number of online users, the current transaction amount, and the current exchange rate. The front-end page needs to refresh and obtain the latest data in real time. This article introduces how to use jQuery and PHP to Display Dynamic numbers.
HTML
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:
The Code is as follows:
Currently online:
JQuery
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:
The Code is 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.
The Code is as follows:
Function update (){
$. GetJSON ("number. php? Jsonp =? ", Function (data ){
Magic_number (data. n );
});
};
SetInterval (update, 5000); // execute once in 5 seconds
Update ();
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:
The Code is as follows:
$ Total_data = array (
'N' => rand (0,999)
);
Echo $ _ GET ['jsonp']. '('. json_encode ($ total_data ).')';
The above is the jQuery + PHP code used to display special effects on dynamic numbers. I hope you will like it.