The idea of today’s experiment is to achieve a page loading effect without refreshing. The specific idea is to use PHP to develop the backend and prepare data for the frontend, then use Ajax technology as a data porter to pull the data from the server to the front end, and finally use JavaScript technology to process the obtained data and display it on the page. .
This experimental data is transmitted and processed in Json format. There are two ways to generate json strings below.
PHP comes with json_encode() and json_decode() methods. However, the decoding method is not commonly used. This is determined by the browser's own working principle. When generating a Json string, we only need to pass the data to be encoded to json_encode().
$obj = arr("first"=>"first_value","second"=>"second_value","three"=>"three_value"); $encode_data = json_encode($arr); var_dump($encode_data);
Compared with the first method, the second method is less automated because it is generated manually, but it is not suitable for processing small amounts of data. In other words, the speed is still very fast.
Note: When using the second method, be sure to use single quotes outside the string and double quotes for the internal key-value data.
For the convenience of demonstration, the second method is adopted.
What is a porter? Here, the data is requested from the server, and then the obtained data is returned to the client where the request was made. Ajax is such a function here.
The following code demonstrates how to create an ajax object and make it work.
After having the data, the remaining work is to make the data look easy to observe. Only in this way can the data have existing value.
The data we get using ajax here is a string data, but what should we do if we want to use this data?
Is this information divided manually? But how to divide it? ···
So we need to use the eval function
// 这样我们就能将字符串成功的转化为一个对象类型的数据eval("var obj="+result);
It is not difficult to find that the links on the page have not changed at all. This is no refresh. Realized page loading!
In this way, our experiment is completed. We can see that in order to provide users with a better user experience, Ajax is definitely the way to go.
The above is the detailed content of Use PHP + JavaScript + Ajax to achieve non-refresh page loading effect (picture). For more information, please follow other related articles on the PHP Chinese website!