天天看點

AJAX原理 之 PHP和資料庫實作AJAX 之 PHP和資料庫實作

AJAX 之 PHP和資料庫實作

ASP我不會,跳過(⊙o⊙)…

簡單形式(原理極其重要)

<script type="text/javascript">

var xmlHttp;

//建立一個XmlHttpRequeset對象
function createXMLHttpRequest(){
    if(window.ActiveXObject){
         xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
     }
    else if(window.XMLHttpRequest){
         xmlHttp = new XMLHttpRequest();
     }
}
//開始一個請求
function startRequest(){
     //調用上方函數
     createXMLHttpRequest();
     //事件句柄指向下一個函數
     xmlHttp.onreadystatechange = handlestatechange;
     xmlHttp.open("GET", "SimpleRespose.xml", true);
     xmlHttp.Send(null);
}

function handlestatechange(){
    if(xmlHttp.readyState == 4){
        if(xmlHttp.status == 200){
             alert("The Server Replied with:" + xmlHttp.responseText)
         }
     }
}
script>
           

實作原理:

  • 點選按鈕,觸發startRequest函數,執行createXMLHttpRequest();語句,建立一個xmlHttpRequest對象
    • 此時xmlHttpRequest.readyState的值是0
  • 再執行Open()語句,跳過xmlHttp.onreadystatechange=handlestatechange;(當作斷點跳過,或函數指針了解)
    • 此時xmlHttpRequest.readyState的值是0
  • 然後運作xmlHttp.onreadystatechange = handlestatechange;
    • 此時xmlHttpRequest.readyState的值是1
  • 再執行Send()語句,跳過xmlHttp.onreadystatechange=handlestatechange;(當作斷點跳過,或函數指針了解)
    • 此時xmlHttpRequest.readyState的值是1
  • 然後運作xmlHttp.onreadystatechange = handlestatechange;
    • 此時xmlHttpRequest.readyState的值是2
  • 再執行Open()語句,跳過xmlHttp.onreadystatechange=handlestatechange;(當作斷點跳過,或函數指針了解)
    • 此時xmlHttpRequest.readyState的值是2
  • 然後運作xmlHttp.onreadystatechange = handlestatechange;
    • 此時xmlHttpRequest.readyState的值是3
  • 再執行Send()語句,跳過xmlHttp.onreadystatechange=handlestatechange;(當作斷點跳過,或函數指針了解)
    • 此時xmlHttpRequest.readyState的值是3
  • 然後運作xmlHttp.onreadystatechange = handlestatechange;
    • 此時xmlHttpRequest.readyState的值是4

我畫分割線的部分,其實它一直在循環運作,不會停止,直到遇到handlestatechange()為止,才結束。

執行個體1:自定義showHint()函數

當使用者在輸入框中鍵入字元時,網頁如何與 web 伺服器進行通信

index_1.html

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script>
function showHint(str){
    var xmlhttp;
    //輸入框為空 str.length==0,則該函數清空 txtHint 占位符的内容,并退出函數
    if (str.length==0){
        document.getElementById("txtHint").innerHTML="";
        return;
    }
    //輸入框不為空,先建立 XMLHttpRequest 對象
    if (window.XMLHttpRequest){
        xmlhttp=new XMLHttpRequest();
    }
    //再當伺服器響應就緒時,點選标簽為txtHint的文本框就執行showHint()函數(即本函數)
    xmlhttp.onreadystatechange=function(){
        if (xmlhttp.readyState==4 && xmlhttp.status==200) {
            document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
        }
    }
    //在"...php?q="+str中q會在php代碼中調用
    xmlhttp.open("GET","/Ajax/gethint.php?q="+str,true);
    xmlhttp.send();
}
</script>
</head>
<body>

<h3>在輸入框中嘗試輸入字母:</h3>
<form action="">
輸入姓名: <input type="text" id="txt1" onkeyup="showHint(this.value)" />
</form>
<p>提示資訊: <span id="txtHint"></span></p>

</body>
</html>
           

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參數,擷取到前面的str值
$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];
      }
    }
  }
}
if ($hint == ""){
  $response="未輸入";
}else{
  $response=$hint;
}
echo $response;   //輸出找到的類似比對值
?>
           

執行個體1:自定義showCustomer()函數

示範網頁如何通過AJAX從資料庫讀取資訊

index_2.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <script>
        function showCustomer(str){
            var xmlhttp;
            //檢查是否已選擇某個客戶。輸入框為空 沒有選擇,則該函數清空 txtHint 占位符的内容,并退出函數
            if (str==""){
                document.getElementById("txtHint").innerHTML="";
                return;
            }
            if (window.XMLHttpRequest){
                xmlhttp=new XMLHttpRequest();
            }
            xmlhttp.onreadystatechange=function(){
                if (xmlhttp.readyState==4 && xmlhttp.status==200){
                    document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
                }
            }
            xmlhttp.open("GET","./getcustomer.php?q="+str,true);
            xmlhttp.send();
        }
    </script>
</head>
<body>

<form action="">
    <select name="customers" onchange="showCustomer(this.value)" >
        <option value="APPLE">Apple Computer, Inc.</option>
        <option value="BAIDU ">BAIDU, Inc</option>
        <option value="Canon">Canon USA, Inc.</option>
    </select>
</form>
<br>
<div id="txtHint">客戶資訊将顯示在這...</div>

</body>
</html>
           

getcustomer.php

這裡不是mysql的表,用到了ADODB是一種 PHP 存取資料庫的中間函式元件。我個人偏向PDO,因為我隻會PDO和mysqli,emmm

下次更改的時候我換成mysqli的形式,這次就照抄了(已更改)

<?php
$q = isset($_GET["q"]) ? $_GET["q"] : '';
$mysqli=new mysqli('localhost','root',123456,'test',3307);    //這裡建議大家端口預設3306
$result=$mysqli->query("select * from client where company='".$q."'");
if (!$mysqli)
{
    die('Could not connect: ' . mysqli_error($mysqli));
}
echo "<table >
<tr>
<th>id</th>
<th>姓名</th>
<th>公司</th>
</tr>";
while($row = $result->fetch_assoc())
{
    echo "<tr>";
    echo "<td>" . $row['id'] . "</td>";
    echo "<td>" . $row['name'] . "</td>";
    echo "<td>" . $row['company'] . "</td>";
    echo "</tr>";
}
echo "</table>";
?>
           

test資料庫、client資料表(用到PHPadmin管理)

AJAX原理 之 PHP和資料庫實作AJAX 之 PHP和資料庫實作

效果圖:

AJAX原理 之 PHP和資料庫實作AJAX 之 PHP和資料庫實作
AJAX原理 之 PHP和資料庫實作AJAX 之 PHP和資料庫實作

執行個體3:示範網頁如何使用 AJAX 來讀取來自 XML 檔案的資訊

示範網頁如何通過AJAX從資料庫讀取資訊

用到一個callback函數建立一個XMLHttpRequest,并從一個TXT檔案中檢索資料(callback函數即回調函數,上篇部落格沒有展開,這裡說下)

  • 如果網站上存在多個 AJAX 任務,就應該為建立 XMLHttpRequest 對象編寫一個标準的函數,并為每個 AJAX 任務調用該函數。
<!DOCTYPE html>
<html>
<head>
<script>

var xmlhttp;

function loadXMLDoc(url,cfunc){
if (window.XMLHttpRequest){
  xmlhttp=new XMLHttpRequest();
  }
xmlhttp.onreadystatechange=cfunc;
xmlhttp.open("GET",url,true);
xmlhttp.send();
}

//注意這個函數就是回調函數,以參數形式傳遞給另一個函數的函數
function myFunction(){
  oadXMLDoc("/try/ajax/ajax_info.txt",function(){
    if (xmlhttp.readyState==4 && xmlhttp.status==200){
      document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
		}
	});
}
</script>
</head>
<body>

<div id="myDiv"><h2>使用 AJAX 修改文本内容</h2></div>
<button type="button" onclick="myFunction()">修改内容</button>

</body>
</html>
           

注意:cfunc出現兩次的位置,類似于前文中簡單形式的了解,但有所不同