跳转到主内容
极星编程网:以代码为星,赴技术山海!

php的ajax实例

当输入j后,会触发ajax效果,从后台获取相应的名字中带有j的数据,并展示在suggestions中。

代码实现如下:

实现ajax需要三个文件,一个是html的表单文件,一个是js的核心文件,一个是php的后台文件。

下面的是html文件,当键盘按下时触发showHint方法,在showHint方法中会有ajax的核心内容,实例化,获取地址,获取数据并展示等等。

立即学习“PHP免费学习笔记(深入)

”;

First Name:onkeyup="showHint(this.value)">Suggestions:下面是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
0 if (strlen($q) > 0){$hint="";for($i=0; $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;?>

相关文章