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

PHP学习笔记(六):通过ajax实时匹配后台的数据

2015-06-28 16:36 796 查看
有两个文件:ajax.html和ajax.php;

通过在ajax.html中输入字符,就可以匹配在ajax.php中存的字符串

ajax.html

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>无标题文档</title>
</head>

<body>
<form>
First Name:
<input type="text" id="txt1" onKeyUp="showHint(this.value)">
</form>
<p>
Suggestions:<span id="txtHint"></span>
</p>

</body>
<script src="jquery.min.js"></script>
<script type="text/javascript">
var xmlHttp;
document.getElementById("txtHint").innerHTML="hh";

function showHint(str){
if(str.length==0){
document.getElementById("txtHint").innerHTML="";
return;
}
xmlHttp=GetXmlHttpObject();
if(xmlHttp==null){
alert("Brower does not support Http Request!");
return;
}

var url="ajax.php";
url+="?q="+str;
url+="&sid="+Math.random();
xmlHttp.onreadystatechange=stateChanged;
xmlHttp.open("GET",url,true);
xmlHttp.send(null);
}

function stateChanged(){
if(xmlHttp.readyState==4 || xmlHttp.readyState=="complete"){
document.getElementById("txtHint").innerHTML=xmlHttp.responseText;
}
}

function GetXmlHttpObject(){
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
//下面这行代码如果直接在Firefox中运行会报错,提示"ActiveXObject is not defined",
//这是因为下面的代码只能运行在IE6和IE5中
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
return xmlHttp;
}
</script>
</html>
ajax.php

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>无标题文档</title>
</head>

<body>
<?php
$a[]="zhao";
$a[]="qian";
$a[]="sun";
$a[]="li";

$q=$_GET["q"];
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="No suggestion";
}
else
{
$response=$hint;
}
echo $response;
?>
</body>
</html>


关于onreadystatechange 事件:

当请求被发送到服务器时,我们需要执行一些基于响应的任务。

每当 readyState 改变时,就会触发 onreadystatechange 事件。

readyState 属性存有 XMLHttpRequest 的状态信息。

下面是 XMLHttpRequest 对象的三个重要的属性:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: