AJAX与PHP

AJAX是什么?

简介

AJAX = Asynchronous JavaScript and XML.

AJAX 是一种用于创建快速动态网页的技术。

AJAX 通过在后台与服务器进行少量数据交换,使网页实现异步更新。这意味着可以在不重载整个页面的情况下,对网页的某些部分进行更新。

传统的网页(不使用 AJAX)如果需要更新内容,必须重载整个页面。

工作原理

AJAX 基于因特网标准,并使用以下技术组合:

  • XMLHttpRequest 对象(与服务器异步交互数据)
  • JavaScript/DOM(显示/取回信息)
  • CSS(设置数据的样式)
  • XML(常用作数据传输的格式)

AJAX 应用程序与浏览器和平台无关的!

实例一:搜索建议

在现在的很多应用中,我们输入文字下方就有提示词,这就是通过ajax实现的,这也是ajax的起源(最早用于谷歌搜索建议)。

index.php:当用户在上面的输入框中键入字符时,会触发 "onkeyup" 事件,从而会执行 "showHint()" 函数,该函数会把搜索框中的内容发送给gethint.php,当收到返回消息后显示出来。

<html>
<head>
    <script>
        function showHint(str)
        {
            if (str.length==0)
            {
                document.getElementById("txtHint").innerHTML="";
                return;
            }
            if (window.XMLHttpRequest)
            {
                // IE7+, Firefox, Chrome, Opera, Safari 浏览器执行的代码
                xmlhttp=new XMLHttpRequest();
            }
            else
            {
                //IE6, IE5 浏览器执行的代码
                xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
            }
            xmlhttp.onreadystatechange=function()
            {
                if (xmlhttp.readyState==4 && xmlhttp.status==200)
                {
                    document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
                }
            }
            xmlhttp.open("GET","gethint.php?q="+str,true);
            xmlhttp.send();
        }
    </script>
</head>
<body>

<p><b>在输入框中输入一个姓名:</b></p>
<form>
    姓名: <input type="text" onkeyup="showHint(this.value)">
</form>
<p>返回值: <span id="txtHint"></span></p>

</body>
</html>
View Code

gethint.php:会与存放名字的数组匹配,然后想浏览器返回匹配结果。

<?php
// 将姓名填充到数组中
$a[]="Anna";
$a[]="Brittany";
$a[]="Cinderella";
$a[]="Diana";
$a[]="Eva";
$a[]="Fiona";
$a[]="Gunda";
$a[]="Hege";
$a[]="Inga";
$a[]="Johanna";
$a[]="Kitty";
$a[]="Linda";
$a[]="Nina";
$a[]="Ophelia";
$a[]="Petunia";
$a[]="Amanda";
$a[]="Raquel";
$a[]="Cindy";
$a[]="Doris";
$a[]="Eve";
$a[]="Evita";
$a[]="Sunniva";
$a[]="Tove";
$a[]="Unni";
$a[]="Violet";
$a[]="Liza";
$a[]="Elizabeth";
$a[]="Ellen";
$a[]="Wenche";
$a[]="Vicky";

//从请求URL地址中获取 q 参数
$q=$_GET["q"];

//查找是否由匹配值, 如果 q>0
if (strlen($q) > 0)
{
    $hint="";
    for($i=0; $i<count($a); $i++)
    {
        if (strtolower($q)==strtolower(substr($a[$i],0,strlen($q))))
        {
            if ($hint=="")
            {
                $hint=$a[$i];
            }
            else
            {
                $hint=$hint." , ".$a[$i];
            }
        }
    }
}

// 如果没有匹配值设置输出为 "no suggestion"
if ($hint == "")
{
    $response="no suggestion";
}
else
{
    $response=$hint;
}

//输出返回值
echo $response;
View Code

实例二:AJAX+XML

下面的实例将演示网页如何通过 AJAX 从 XML 文件读取信息,原理与前面相似。

index.php:当用户在上面的下拉列表中选择某张 CD 时,会执行名为 "showCD()" 的函数。该函数由 "onchange" 事件触发:

<html>
<head>
    <script>
        function showCD(str)
        {
            if (str=="")
            {
                document.getElementById("txtHint").innerHTML="";
                return;
            }
            if (window.XMLHttpRequest)
            {
                // IE7+, Firefox, Chrome, Opera, Safari 浏览器执行
                xmlhttp=new XMLHttpRequest();
            }
            else
            {
                // IE6, IE5 浏览器执行
                xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
            }
            xmlhttp.onreadystatechange=function()
            {
                if (xmlhttp.readyState==4 && xmlhttp.status==200)
                {
                    document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
                }
            }
            xmlhttp.open("GET","getxml.php?q="+str,true);
            xmlhttp.send();
        }
    </script>
</head>
<body>

<form>
    Select a CD:
    <select name="cds" onchange="showCD(this.value)">
        <option value="">Select a CD:</option>
        <option value="Bob Dylan">Bob Dylan</option>
        <option value="Bonnie Tyler">Bonnie Tyler</option>
        <option value="Dolly Parton">Dolly Parton</option>
    </select>
</form>
<div id="txtHint"><b>CD info will be listed here...</b></div>

</body>
</html>
View Code

getxml.php:PHP 脚本加载 XML 文档,"cd_catalog.xml",运行针对 XML 文件的查询,并以 HTML 返回结果:

<?php
$q=$_GET["q"];

$xmlDoc = new DOMDocument();
$xmlDoc->load("cd_catalog.xml");

$x=$xmlDoc->getElementsByTagName('ARTIST');

for ($i=0; $i<=$x->length-1; $i++)
{
    // 处理元素节点
    if ($x->item($i)->nodeType==1)
    {
        if ($x->item($i)->childNodes->item(0)->nodeValue == $q)
        {
            $y=($x->item($i)->parentNode);
            break;
        }
    }
}

$cd=($y->childNodes);


for ($i=0;$i<$cd->length;$i++)
{
    // 处理元素节点
    if ($cd->item($i)->nodeType==1)
    {
        echo("<b>" . $cd->item($i)->nodeName . ":</b> ");
        echo($cd->item($i)->childNodes->item(0)->nodeValue);
        echo("<br>");
    }
}
View Code

实例三:AJAX+Mysql

通过AJAX从mysql获取数据,原理与前面两个相似。

使用到的 Websites 表 SQL 文件:websites.sql

CREATE DATABASE test;  #创建use库
use test;          
source C:Users20928Downloadswebsites.sql;   #导入sql,改成自己的路径
show tables;        #查看是否创建成功

index.php:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>菜鸟教程(runoob.com)</title>
    <script>
        function showSite(str)
        {
            if (str=="")
            {
                document.getElementById("txtHint").innerHTML="";
                return;
            }
            if (window.XMLHttpRequest)
            {
                // IE7+, Firefox, Chrome, Opera, Safari 浏览器执行代码
                xmlhttp=new XMLHttpRequest();
            }
            else
            {
                // IE6, IE5 浏览器执行代码
                xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
            }
            xmlhttp.onreadystatechange=function()
            {
                if (xmlhttp.readyState==4 && xmlhttp.status==200)
                {
                    document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
                }
            }
            xmlhttp.open("GET","getmysql.php?q="+str,true);
            xmlhttp.send();
        }
    </script>
</head>
<body>

<form>
    <select name="users" onchange="showSite(this.value)">
        <option value="">选择一个网站:</option>
        <option value="1">Google</option>
        <option value="2">淘宝</option>
        <option value="3">菜鸟教程</option>
        <option value="4">微博</option>
        <option value="5">Facebook</option>
    </select>
</form>
<br>
<div id="txtHint"><b>网站信息显示在这里……</b></div>

</body>
</html>
View Code

getmysql.php:

<?php
$q = isset($_GET["q"]) ? intval($_GET["q"]) : '';

if(empty($q)) {
    echo '请选择一个网站';
    exit;
}

$con = mysqli_connect('localhost','root','');
if (!$con)
{
    die('Could not connect: ' . mysqli_error($con));
}
// 选择数据库
mysqli_select_db($con,"test");
// 设置编码,防止中文乱码
mysqli_set_charset($con, "utf8");

$sql="SELECT * FROM Websites WHERE id = '".$q."'";

$result = mysqli_query($con,$sql);
if (!$result) {
    printf("Error: %s
", mysqli_error($con));
    exit();
}

echo "<table border='1'>
<tr>
<th>ID</th>
<th>网站名</th>
<th>网站 URL</th>
<th>Alexa 排名</th>
<th>国家</th>
</tr>";

while($row = mysqli_fetch_array($result))
{
    echo "<tr>";
    echo "<td>" . $row['id'] . "</td>";
    echo "<td>" . $row['name'] . "</td>";
    echo "<td>" . $row['url'] . "</td>";
    echo "<td>" . $row['alexa'] . "</td>";
    echo "<td>" . $row['country'] . "</td>";
    echo "</tr>";
}
echo "</table>";

mysqli_close($con);
View Code

参考链接:

1. https://www.runoob.com/php/php-ajax-intro.html

2. https://www.runoob.com/php/php-ajax-php.html?

3. https://www.runoob.com/php/php-ajax-xml.html

4. https://www.runoob.com/php/php-ajax-database.html

原文地址:https://www.cnblogs.com/lfri/p/12228973.html