
这篇文章给大家讲述了PHP 实例 - AJAX 实时搜索的教程。
PHP 实例 - AJAX 实时搜索
AJAX 可为用户提供更友好、交互性更强的搜索体验。
AJAX Live Search
在下面的实例中,我们将演示一个实时的搜索,在您键入数据的同时即可得到搜索结果。
实时的搜索与传统的搜索相比,具有很多优势:
当键入数据时,就会显示出匹配的结果
当继续键入数据时,对结果进行过滤
如果结果太少,删除字符就可以获得更宽的范围
在下面的文本框中输入 "HTML",搜索包含 HTML 的页面:
上面实例中的结果在一个 XML 文件(links.xml)中进行查找。为了让这个例子小而简单,我们只提供 6 个结果。
实例解释 - HTML 页面
当用户在上面的输入框中键入字符时,会执行 "showResult()" 函数。该函数由 "onkeyup" 事件触发:
function showResult(str)
{
if (str.length==0)
{
document.getElementById("livesearch").innerHTML="";
document.getElementById("livesearch").style.border="0px";
return;
}
if (window.XMLHttpRequest)
{// IE7+, Firefox, Chrome, Opera, Safari 浏览器执行
xmlhttp=new XMLHttpRequest();
}
else
{// IE6, IE5 浏览器执行
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("livesearch").innerHTML=xmlhttp.responseText;
document.getElementById("livesearch").style.border="1px solid #A5ACB2";
}
}
xmlhttp.open("GET","livesearch.php?q="+str,true);
xmlhttp.send();
}
源代码解释:
如果输入框是空的(str.length==0),该函数会清空 livesearch 占位符的内容,并退出该函数。
如果输入框不是空的,那么 showResult() 会执行以下步骤:
创建 XMLHttpRequest 对象
创建在服务器响应就绪时执行的函数
向服务器上的文件发送请求
请注意添加到 URL 末端的参数(q)(包含输入框的内容)
PHP 文件
上面这段通过 JavaScript 调用的服务器页面是名为 "livesearch.php" 的 PHP 文件。
"livesearch.php" 中的源代码会搜索 XML 文件中匹配搜索字符串的标题,并返回结果:
$xmlDoc=new DOMDocument();
$xmlDoc->load("links.xml");
$x=$xmlDoc->getElementsByTagName('link');
// 从 URL 中获取参数 q 的值
$q=$_GET["q"];
// 如果 q 参数存在则从 xml 文件中查找数据
if (strlen($q)>0)
{
$hint="";
for($i=0; $i<($x->length); $i++)
{
$y=$x->item($i)->getElementsByTagName('title');
$z=$x->item($i)->getElementsByTagName('url');
if ($y->item(0)->nodeType==1)
{
// 找到匹配搜索的链接
if(stristr($y->item(0)->childNodes->item(0)->nodeValue,$q))
{
if ($hint=="")
{
$hint="" .
$y->item(0)->childNodes->item(0)->nodeValue . "";
}
else
{
$hint=$hint . "
" .
$y->item(0)->childNodes->item(0)->nodeValue . "";
}
}
}
}
}
// 如果没找到则返回 "no suggestion"
if ($hint=="")
{
$response="no suggestion";
}
else
{
$response=$hint;
}
// 输出结果
echo $response;
?>
如果 JavaScript 发送了任何文本(即 strlen($q) > 0),则会发生:
加载 XML 文件到新的 XML DOM 对象
遍历所有的
元素,以便找到匹配 JavaScript 所传文本</p><p>在 "$response" 变量中设置正确的 URL 和标题。如果找到多于一个匹配,所有的匹配都会添加到变量。</p><p>如果没有找到匹配,则把 $response 变量设置为 "no suggestion"。</p><a href='https://www.eolink.com?utm=jiasou' target='_blank'><img style='width:100%;height:100%' src='https://www.eolink.com/news/zb_users/upload/2022/08/20220805174511165969271139602.jpg'></a><br>
<p>
<strong>版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。</strong>
</p></div>
<div class="article_footer clear">
<div class="fr tag">标签:<a href="https://www.eolink.com/news/tags-985.html">文件</a>
</div>
<div class="bdsharebuttonbox fl share">
<div class="share-widget fl">
<div class="social-share" data-sites="wechat,weibo, qq, qzone"></div>
</div>
</div>
</div>
<!-- 广告位ad4 -->
<div class="post-navigation clear">
<div class="post-previous fl">
<span>上一篇:</span><a href="https://www.eolink.com/news/post/4888.html">php中常用的采集函数的总结,值得收藏!(php数据抓取)</a>
</div>
<div class="post-next fr">
<span>下一篇:</span><a href="https://www.eolink.com/news/post/4890.html">php开发中PhpStorm本地断点调试的方法步骤!</a>
</div>
</div>
</div>
<div class="related_article">
<div class="box_title clear">
<span><i class="icon fa fa-paper-plane"></i>相关文章</span>
</div>
<div class="related_list clear">
<article class="fl">
<div class="related_img"><a href="https://www.eolink.com/news/post/89100.html"><img src="https://www.eolink.com/news/zb_users/theme/zblog5_news/image/random_img/2.jpg"></a></div>
<div class="related_detail">
<h3><a href="https://www.eolink.com/news/post/89100.html" title="java中的接口是类吗">java中的接口是类吗</a></h3>
<div class="meta">
<span><i class="fa fa-eye"></i>278</span>
<span><i class="fa fa-clock-o"></i>2022-06-17</span>
</div>
</div>
</article>
<article class="fl">
<div class="related_img"><a href="https://www.eolink.com/news/post/89090.html"><img src="https://www.eolink.com/news/zb_users/theme/zblog5_news/image/random_img/9.jpg"></a></div>
<div class="related_detail">
<h3><a href="https://www.eolink.com/news/post/89090.html" title="Spring中的aware接口详情">Spring中的aware接口详情</a></h3>
<div class="meta">
<span><i class="fa fa-eye"></i>278</span>
<span><i class="fa fa-clock-o"></i>2022-06-17</span>
</div>
</div>
</article>
<article class="fl">
<div class="related_img"><a href="https://www.eolink.com/news/post/89057.html"><img src="https://www.eolink.com/news/zb_users/theme/zblog5_news/image/random_img/4.jpg"></a></div>
<div class="related_detail">
<h3><a href="https://www.eolink.com/news/post/89057.html" title="Python接口自动化之文件上传/下载接口怎么实现">Python接口自动化之文件上传/下载接口怎么实现</a></h3>
<div class="meta">
<span><i class="fa fa-eye"></i>278</span>
<span><i class="fa fa-clock-o"></i>2022-06-17</span>
</div>
</div>
</article>
</div>
</div>
<div id="comment" class="post-comment clearfix sb br mt">
<p id="comments-title" class="c-title mb bn"><span><i class="fa fa-pencil"></i> 发表评论</span></p>
<div class="compost">
<form id="frmSumbit" target="_self" method="post" action="https://www.eolink.com/news/zb_system/cmd.php?act=cmt&postid=4889&key=e0f5c17823f31c40fa89c52f6f8b8a61">
<input type="hidden" name="inpId" id="inpId" value="4889"/>
<input type="hidden" name="inpRevID" id="inpRevID" value="0"/>
<div class="com-name">
<a rel="nofollow" id="cancel-reply" href="#comments" style="display:none;">取消回复</a>
</div>
<div class="com-info">
<ul>
<li>
<span class="hide" for="author"></span>
<input class="ipt" type="text" name="inpName" id="inpName" value="" tabindex="2" placeholder="昵称(必填)">
</li>
<li>
<span class="hide" for="author"></span>
<input class="ipt" type="text" name="inpEmail" id="inpEmail" value="" tabindex="3" placeholder="邮箱">
</li>
<li>
<span class="hide" for="author"></span>
<input class="ipt" type="text" name="inpHomePage" id="inpHomePage" value="" tabindex="4" placeholder="网址">
</li>
</ul>
</div>
<div class="com-box">
<textarea placeholder="来都来了,说点什么吧..." class="textarea" name="txaArticle" id="txaArticle" cols="5" rows="5" tabindex="1"></textarea>
</div>
<div class="com-info"><button class="com-submit br brightness" name="sumbit" type="submit" tabindex="5" onclick="return zbp.comment.post()">发布评论</button></div>
</form>
</div> <div class="comment-list mt">
<p class="no-comment"><i class="iconfont icon-sofa"></i> 暂时没有评论,来抢沙发吧~</p> <span id="AjaxCommentBegin"></span>
<div class="pagination pagination-multi">
<ul>
</ul>
</div>
<span id="AjaxCommentEnd"></span>
</div>
</div>
</div>
</div>
<div class="sidebar">
<div id="newmodule" class="part clear 推荐文章">
<div class="top">
<h3 class="title">推荐文章</h3>
</div>
<div class="side newmodule"><ul><ul class="hot_posts"> <li><h4><a href="https://www.eolink.com/news/post/16753.html" title="接口调用是什么意思?几种常用接口调用方式">接口调用是什么意思?几种常用接口调用方式</a></h4></li><li><h4><a href="https://www.eolink.com/news/post/64809.html" title="接口设计(接口设计原则)">接口设计原则</a></h4></li><li><h4><a href="https://www.eolink.com/news/post/9069.html" title="API接口管理,8 款在线 API 接口文档管理工具;好用!">8款在线 API 接口文档管理工具</a></h4></li><li><h4><a href="https://www.eolink.com/news/post/64179.html" title="api管理系统">api管理系统是什么?</a></h4></li><li><h4><a href="https://www.eolink.com/news/post/17828.html" title="什么是接口调试?接口调试的步骤有哪些?">什么是接口调试?接口调试的步骤有哪些?</a></h4></li><li><h4><a href="https://www.eolink.com/news/post/63728.html" title="api 接口管理系统(接口统一管理平台)">api 接口管理系统有哪些?</a></h4></li><li><h4><a href="https://www.eolink.com/news/post/77372.html" title="接口测试常用测试方法,多线程免费手机短信压力测试,支持云端获取接口">接口测试有几种测试方法</a></h4></li><li><h4><a href="https://www.eolink.com/news/post/43657.html" title="api文档生成(api接口文档系统)">API文档生成工具有哪些?</a></h4></li><li><h4><a href="https://www.eolink.com/news/post/66400.html" title="微服务和api网关区别(微服务网关技术选型)">微服务和api网关区别</a></h4></li><li><h4><a href="https://www.eolink.com/news/post/64163.html" title="交换机配置步骤">交换机配置步骤</a></h4></li></ul></ul></div>
</div>
<div id="divPrevious" class="part clear previous">
<div class="top">
<h3 class="title">最近发表</h3>
</div>
<div class="side divPrevious"><ul><li><a title="多平台统一管理软件接口,如何实现多平台统一管理软件接口" href="https://www.eolink.com/news/post/89103.html">多平台统一管理软件接口,如何实现多平台统一管理软件接口</a></li>
<li><a title="Flask接口签名sign原理与实例代码浅析" href="https://www.eolink.com/news/post/89102.html">Flask接口签名sign原理与实例代码浅析</a></li>
<li><a title="java中的接口是类吗" href="https://www.eolink.com/news/post/89100.html">java中的接口是类吗</a></li>
<li><a title="vue项目接口域名动态的获取方法" href="https://www.eolink.com/news/post/89099.html">vue项目接口域名动态的获取方法</a></li>
<li><a title="zookeeper python接口实例详解" href="https://www.eolink.com/news/post/89097.html">zookeeper python接口实例详解</a></li>
<li><a title="Iterator与LIstIterator接口在java中的区别有哪些" href="https://www.eolink.com/news/post/89096.html">Iterator与LIstIterator接口在java中的区别有哪些</a></li>
<li><a title="c#自定义Attribute获取接口实现示例代码" href="https://www.eolink.com/news/post/89095.html">c#自定义Attribute获取接口实现示例代码</a></li>
<li><a title="hdml指的是什么接口" href="https://www.eolink.com/news/post/89093.html">hdml指的是什么接口</a></li>
<li><a title="分析EBS常用接口表" href="https://www.eolink.com/news/post/89092.html">分析EBS常用接口表</a></li>
<li><a title="java 单机接口限流处理方案" href="https://www.eolink.com/news/post/89091.html">java 单机接口限流处理方案</a></li>
</ul></div>
</div>
<div id="hot_posts" class="part clear hot_posts">
<div class="top">
<h3 class="title">热评文章</h3>
</div>
<ul class="hot_posts"><li><h4><a href="https://www.eolink.com/news/post/15822.html" title="在线接口文档管理工具推荐,支持在线测试,HTTP接口文档">在线接口文档管理工具推荐,支持在线测试,HTTP接口</a></h4></li><li><h4><a href="https://www.eolink.com/news/post/15841.html" title="开源的在线接口文档wiki工具Mindoc的介绍与使用,五款WEB前端工程师高效的在线接口文档管理工具">开源的在线接口文档wiki工具Mindoc的介绍与使</a></h4></li><li><h4><a href="https://www.eolink.com/news/post/17591.html" title="如何优雅的进行接口设计?接口设计的六大原则是什么?">如何优雅的进行接口设计?接口设计的六大原则是什么?</a></h4></li><li><h4><a href="https://www.eolink.com/news/post/16804.html" title="什么是API测试,api检测公司">什么是API测试,api检测公司</a></h4></li><li><h4><a href="https://www.eolink.com/news/post/29017.html" title="遇到百度网址安全中心提醒您该页面可能存在钓鱼欺诈信息的处理解决办法">遇到百度网址安全中心提醒您该页面可能存在钓鱼欺诈信息</a></h4></li><li><h4><a href="https://www.eolink.com/news/post/25723.html" title="软件接口设计怎么做?前后端分离软件接口设计思路">软件接口设计怎么做?前后端分离软件接口设计思路</a></h4></li></ul> </div> </div>
</div>
</section>
</div>
<footer class="p-footer">
<div class="contant_box">
<div class="discover_tmt">
<h5 class="" style="font-size: 1px; color: white;">Eolink</h5>
<div class="text_box">
<a href="https://www.jiasou.cn/article/" title="toB数字化营销SEO" style="font-size: 1px; color: white;">加搜toBSEO</a>
<a href="https://www.finclip.com/news/category-1.html" title="小程序工具" style="font-size: 1px; color: white;">前端框架</a>
<a href="https://www.jia-ai.com/info/" title="小红书营销攻略" style="font-size: 1px; color: white;">小红书营销攻略</a>
<a href="https://www.yanyin.tech/cms/" title="生物研究资讯" style="font-size: 1px; color: white;">生物研究资讯</a>
<a href="https://www.finclip.com/news/" title="FinClip 技术文档" style="font-size: 1px; color: white;">小程序容器帮助中心</a>
<a href="https://www.finclip.com/news/article/" title="小程序开发行业洞察" style="font-size: 1px; color: white;">小程序开发行业洞察</a>
<a href="https://www.foneplatform.com/jscms/" title="全面预算管理资讯" style="font-size: 1px; color: white;">全面预算管理资讯</a>
<a href="https://www.weiling.cn/article/" title="企微SCRM客户管理干货" style="font-size: 1px; color: white;">企微SCRM客户管理干货</a>
<a href="https://www.vbasm.com/zh/" title="数据筛选平台" style="font-size: 1px; color: white;">数据筛选平台"</a>
<a href="https://www.i2cool.com.cn/tideflow/" title="无电制冷行业资讯" style="font-size: 1px; color: #22292D;">无电制冷行业资讯</a>
</div> </div>
<div class="collaboration_box">
</div>
<div class="we_img_box clear">
<div class="img_box">
<img src="https://www.eolink.com/news/zb_users/theme/zblog5_news/image/ewm.png" alt="" class="hover_tmt">
</div>
</div>
</div>
<p class="info">© 2023 XWNews <a href="#" target="_blank" rel="nofollow">京ICP备1111040123号-1</a>
<span>
<a href="https://www.zblogcn.com/">版权归zblog所有</a></span>
</p>
</footer>
<div id="backtop" class="backtop">
<div class="bt-box top">
<i class="fa fa-angle-up fa-2x"></i>
</div>
</div>
<script type='text/javascript' src="https://www.eolink.com/news/zb_users/theme/zblog5_news/script/custom.js"></script>
<script type='text/javascript' src="https://www.eolink.com/news/zb_users/theme/zblog5_news/script/nav.js"></script>
<link rel="stylesheet" href="https://www.eolink.com/news/zb_users/theme/zblog5_news/share/css/share.min.css">
<script src="https://www.eolink.com/news/zb_users/theme/zblog5_news/share/js/jquery.share.min.js"></script>
<!-- Initialize Swiper -->
<script>
var swiper = new Swiper('.swiper-container', {
pagination: '.swiper-pagination',
paginationClickable: true,
loop: true,
autoplay:2000,
nextButton: '.swiper-button-next',
prevButton: '.swiper-button-prev',
spaceBetween: 30,
effect: 'fade',
});
</script>
<script>
var _hmt = _hmt || [];
(function() {
var hm = document.createElement("script");
hm.src = "https://hm.baidu.com/hm.js?556b23f3809179e610086ba68e9a0c89";
var s = document.getElementsByTagName("script")[0];
s.parentNode.insertBefore(hm, s);
})();
</script>
<script>
(()=>{const e="https://analyze.jiasou.cc/api/v1/page_view/report/",n="9e1fab3b60d44b87a9a33c16962df4b1";let t=null;const o=new Proxy({},{get:(e,n)=>localStorage.getItem(window.btoa(n)),set:(e,n,t)=>!!t&&(localStorage.setItem(window.btoa(n),t),!0)});new Promise((t=>{if(o.fingerprint)t();else{const a=function(){var e={};if(e.userAgent=navigator.userAgent||"",e.plugins=[],navigator.plugins&&navigator.plugins.length>0)for(var n=0;n<navigator.plugins.length;n++){var t={name:navigator.plugins[n].name||"",filename:navigator.plugins[n].filename||"",description:navigator.plugins[n].description||""};e.plugins.push(t)}e.languages=navigator.languages||[navigator.language||""],e.timezone=(new Date).getTimezoneOffset(),e.screenResolution={width:window.screen.width||0,height:window.screen.height||0,pixelDepth:window.screen.pixelDepth||0,colorDepth:window.screen.colorDepth||0};var o=document.createElement("canvas").getContext("2d"),a=[],i=["monospace","sans-serif","serif"];for(n=0;n<i.length;n++){var r=i[n];o.font="12px "+r,o.measureText("abcdefghijklmnopqrstuvwxyz0123456789").width>0&&a.push(r)}return e.fonts=a,e.cookieEnabled=navigator.cookieEnabled||!1,e.localStorage=void 0!==window.localStorage,e.sessionStorage=void 0!==window.sessionStorage,e.doNotTrack="1"===navigator.doNotTrack||"1"===window.doNotTrack||"1"===navigator.msDoNotTrack||"yes"===navigator.doNotTrack,e}();fetch(`${e}u/`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({key:n,f:window.btoa(JSON.stringify(a))})}).then((e=>{console.debug("browser fingerprint sent"),200===e.status&&e.json().then((e=>{console.debug("browser fingerprint received",e),o.fingerprint=e.fp,t()}))}))}})).then((()=>{e&&o.fingerprint&&fetch(e+`?${new URLSearchParams({token:n}).toString()}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({c:window.btoa(JSON.stringify({u:o.fingerprint,l:window.location.href,r:document.referrer}))})}).then((e=>{200==e.status&&e.json().then((e=>{e.track_id&&(t=e.track_id)}))}))})),window.addEventListener("beforeunload",(async n=>{t&&fetch(e+`?${new URLSearchParams({track_id:t}).toString()}`,{method:"GET",headers:{"Content-Type":"text/plain"},keepalive:!0}),n.returnValue=""}))})();
</script><script language="javascript" src="https://www.eolink.com/news/zb_users/plugin/ZF_ad/js/index.js?id=176"></script>
<script language="javascript" src="https://www.eolink.com/news/zb_users/plugin/ZF_ad/js/ZF_ad__cookie.js"></script>
</body>
</html><!--92.09 ms , 18 queries , 1743kb memory , 0 error-->