温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

php的ajax的实例用法

发布时间:2021-07-26 17:42:05 来源:亿速云 阅读:106 作者:chen 栏目:开发技术

本篇内容主要讲解“php的ajax的实例用法”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“php的ajax的实例用法”吧!

php的ajax的实例用法

当输入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;
?>

到此,相信大家对“php的ajax的实例用法”有了更深的了解,不妨来实际操作一番吧!这里是亿速云网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI