PHP和ajax(一)
阿新 • • 發佈:2018-12-23
本篇文章是php中使用ajax的案例,該案例有三個檔案組成:html檔案,js檔案,php檔案。這個案例實現了一個簡單的功能:有一個文字框,當在文字框中輸入內容的時候,在頁面上會有提示資訊展示出來,如下圖所示:
一、html頁面:input.html
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>Page Title</title> <meta name="viewport" content="width=device-width, initial-scale=1"> </head> <body> name: <input type="text" name="name" id="txt01"> <p> Suggestion: <span id="txtHint"></span> </p> <script src="input.js"></script> </body> </html>
二、js頁面:input.js
(function(){// 用於獲取xmlHttpRequest function GetXmlHttpObject(){ var xmlHttp = null; try{ // Firfox, Opera 8+, safari xmlHttp = new XMLHttpRequest(); }catch(e){ try{ // Internet Explorer xmlHttp = new ActiveXObject("Msxml2.XMLHTTP"); }catch(e){ xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); } } return xmlHttp; } var xmlHttp; // 展示hint function showHint(str){ if(str.length == 0){ document.getElementById("txtHint").innerHTML = ""; return; } // 建立xmlHttp xmlHttp = GetXmlHttpObject(); if(xmlHttp==null){ console.log("Brower does not suppert Http Request."); return; } xmlHttp.onreadystatechange = stateChanged; url = generateUrl("input.php",str); console.log(url); xmlHttp.open("GET",url,true); xmlHttp.send(null); } // 拼接url,拼接一個隨機數,防止使用快取 function generateUrl(php_path,str){ var url = php_path+"?q="+str; url += "&sid="+Math.random(); return url; } function stateChanged(){ if(xmlHttp.readyState == 4 || xmlHttp.readyState == "complete"){ document.getElementById("txtHint").innerHTML = xmlHttp.responseText; } } // 新增監聽事件 var inputObj = document.getElementById("txt01"); inputObj.removeEventListener("keyup",function(){ showHint(inputObj.value); }); inputObj.addEventListener("keyup",function(){ showHint(inputObj.value); }); })();
三、php頁面:input.php
<?php // 填充陣列 $a = array("Anna", "Brittany", "Cinderella", "Diana", "Eva", "Fiona", "Gunda", "Hege", "Inga", "Johanna", "Kitty", "Linda", "Nina", "Ophelia", "Petunia", "Amanda", "Raquel", "Cindy", "Doris", "Eve", "Evita", "Sunniva", "Tove", "Unni", "Violet", "Liza", "Elizabeth", "Ellen", "Wenche", "Vicky"); #print_r($a); // 從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” // or to the current values if($hint === ""){ $response = "no suggestion"; }else{ $response = $hint; } // 輸出$response echo $response; } ?>