Home > Backend Development > PHP Tutorial > Use PHP + JavaScript + Ajax to achieve non-refresh page loading effect (picture)

Use PHP + JavaScript + Ajax to achieve non-refresh page loading effect (picture)

黄舟
Release: 2023-03-06 14:34:01
Original
1516 people have browsed it

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. .

Data Source Factory

This experimental data is transmitted and processed in Json format. There are two ways to generate json strings below.

Json generation method 1

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);
Copy after login

Json generation method 2

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.

<?php
header("Content-Type:text/html;charset=utf-8");// 制作一个Json信息
echo &#39;{"city":"大连","temp":"27°C","WD":"东南风"}&#39;;
?>
Copy after login

For the convenience of demonstration, the second method is adopted.

Data porter

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.

<script>
        function f1(){
            alert(&#39;即将弹出数据&#39;);            
            var ajax;           
             if(window.XMLHttpRequest){
                ajax = new XMLHttpRequest();
            }else{
                ajax = new ActiveObject("Microsoft.XMLHTTP");
            }            // 给Ajax设置事件
            ajax.onreadystatechange = function(){
                if(ajax.readyState==4){
                    alert(ajax.responseText);
                    document.getElementById(&#39;response&#39;).innerHTML=ajax.responseText;
                }
            }            // 如果以GET请求方式请求数据的话,为了防止特殊字符,及中文的干扰我们要使用JavaScript的一个encodeURIComponent(raw_data);进行安全编码
            ajax.open(&#39;get&#39;,&#39;./forajax.php&#39;);            
            // 使用POST请求方式的时候,其原理是模拟表单提交,所以需要加上头信息,但是要放到open方法后面
            ajax.setRequestHeader("content-type","application/x-www-urlencoded");
            ajax.send(null);
        }    </script>
Copy after login

Data Processor

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? ···

Conversion type

So we need to use the eval function

// 这样我们就能将字符串成功的转化为一个对象类型的数据eval("var obj="+result);
Copy after login

Processing display

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" " 
<html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>使用Ajax获取数据,交给JavaScript处理</title>
<script>
    function getWeather() {
        var ajaxclient;        
        if(window.XMLHttpRequest){
            ajaxclient = new XMLHttpRequest();  
        }else {
            ajaxclient = new ActiveObject("Microsoft.XMLHTTP"); 
        }        // 当数据完整返回的时候触发
        ajaxclient.onreadystatechange = function() {
            if(ajaxclient.readyState==4){                // 使用eval函数来把字符串转换为一个对象
                eval("var result=" + ajaxclient.responseText);                //alert("服务器返回的信息为:"+result);
                document.getElementById("city").innerHTML=result.city;
                document.getElementById("temp").innerHTML=result.temp;
                document.getElementById("wd").innerHTML=result.WD;
            }
        }        // 开始发送请求
        ajaxclient.open(&#39;get&#39;,&#39;./forjson.php&#39;);
        ajaxclient.send(null);

    }</script>
    </head><body><h1>使用Ajax异步获取天气数据,再使用JavaScript处理数据
    </h1><button name="btn" onclick="getWeather()">获取并显示数据</button>
    <p><table width="200" border="1" summary="使用ajax无刷新获取数据,在使用JavaScript处理数据。">
  <caption>
    详细信息  </caption>
  <tr>
    <td>城市</td>
    <td>温度</td>
    <td>风向</td>
  </tr>
  <tr>
    <td><span id="city"></span></td>
    <td><span id="temp"></span></td>
    <td><span id="wd"></span></td>
  </tr></table></p></body></html>
Copy after login

Result display

Initial page

Use PHP + JavaScript + Ajax to achieve non-refresh page loading effect (picture)

After clicking the button

Use PHP + JavaScript + Ajax to achieve non-refresh page loading effect (picture)

It is not difficult to find that the links on the page have not changed at all. This is no refresh. Realized page loading!

Summary

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template