程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> 網頁編程 >> PHP編程 >> 關於PHP編程 >> php的ajax簡單實例

php的ajax簡單實例

編輯:關於PHP編程



當輸入j後,會觸發ajax效果,從後台獲取相應的名字中帶有j的數據,並展示在suggestions中。

代碼實現如下:

實現ajax需要三個文件,一個是html的表單文件,一個是js的核心文件,一個是php的後台文件。

下面的是html文件,當鍵盤按下時觸發showHint方法,在showHint方法中會有ajax的核心內容,實例化,獲取地址,獲取數據並展示等等。
復制代碼 代碼如下:
<html>
<head>
<script src="clienthint.js"></script>
</head>

<body>

<form>
First Name:
<input type="text" id="txt1"
onkeyup="showHint(this.value)">
</form>

<p>Suggestions: <span id="txtHint"></span></p>

</body>
</html>

 

下面是js的內容clienthint.js。
復制代碼 代碼如下:
var xmlHttp

function showHint(str)
{
if (str.length==0)
 {
 document.getElementById("txtHint").innerHTML=""
 return
 }
//獲取xmlHttpObject對象,如果為空,提示浏覽器不支持ajax
xmlHttp=GetXmlHttpObject()
if (xmlHttp==null)
 {
 alert ("Browser does not support HTTP Request")
 return
 }
 //獲取url
var url="gethint.php"
url=url+"?q="+str
url=url+"&sid="+Math.random()
 //回調函數,執行動作
xmlHttp.onreadystatechange=stateChanged
 //open
xmlHttp.open("GET",url,true)
xmlHttp.send(null)
}

function stateChanged()
{
if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
{
//將獲取的信息插入到txtHint中
document.getElementById("txtHint").innerHTML=xmlHttp.responseText
}
}


//獲取xml對象
function GetXmlHttpObject()
{
var xmlHttp=null;
try
{
// Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
}
catch (e)
{
// Internet Explorer
try
 {
 xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
 }
catch (e)
 {
 xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
 }
}
return xmlHttp;
}

下面是php的內容。根據ajax對象傳入的參數,獲取相應的數據。
復制代碼 代碼如下:
<?php
// Fill up array with names
$a[]="Anna";
$a[]="Brittany";
$a[]="Cinderella";
$a[]="Diana";
$a[]="Eva";
$a[]="Fiona";
$a[]="Gunda";
$a[]="Hege";
$a[]="Inga";
$a[]="Johanna";
$a[]="Jiqing";
$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";

//get the q parameter from URL
$q=$_GET["q"];

//lookup all hints from array if length of 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];
     }
   }
 }
}

//Set output to "no suggestion" if no hint were found
//or to the correct values
if ($hint == "")
{
$response="no suggestion";
}
else
{
$response=$hint;
}

//output the response
echo $response;
?>

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved