您的位置:首页 > 编程语言 > PHP开发

php的ajax简单实例

2016-04-20 21:59 639 查看
很早就听闻ajax的名声,但是却一直不知道怎么用,今天自己捣鼓了一下,竟然会用了,哈哈哈哈。

为了防止我自己忘记,现在把这个简单的实例记录下。这个实例是网上搜的,文末附上链接。

首先你得有自己的服务器,这个我已经采用xampp配置好了。

实现ajax需要三个文件,一个是html的表单文件,一个是js的核心文件,一个是php的后台文件。具体的文件如下所示:

下面的是test.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,太长了,我就折叠了,其中的url也可以写成这样http://localhost/shen/test/gethint.php。效果是一样的。

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


View Code
首先把所有的文件都放在Xampp/htdocs(xampp安装位置)文件夹中,我又新建了两个文件夹,于是路径就变成了Xampp/htdocs/shen/test。

接下去在浏览器中输入以下地址http://localhost/shen/test/test.html,当输入a后,会触发ajax效果,从后台获取相应的名字中带有j的数据,并展示在suggestions中。



本文转自http://www.jb51.net/article/47329.htm
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: