首页博客网络编程
搜索特定数据最方便的方法之一是 AJAX 搜索框。它也被称为实时搜索,因为它对用户的输入做出反应。
当用户键入时,实时搜索会显示有关如何完成关键字的建议。输入一个字符可能就足以使框自动完成。要创建这样的搜索引擎,您必须结合AJAX和PHP。我们将在下面的文章中展示此过程。
通过使用 AJAX 和 PHP,您可以创建实时搜索 Web 应用程序。
用户更喜欢实时搜索,因为它的速度和键入时提供的建议。
您将在下面找到一个简单的 AJAX PHP 搜索应用程序的示例。示例中的结果取自此示例。
为了使示例简单易懂,我们将搜索限制为三个可能的值。它们将与我们在 AJAX 表单教程中使用的相同:
例复制
<form> <select name="users" onchange="showUser(this.value)"> <option value="">Select a person:</option> <option value="johny">Johny Dawkins</option> <option value="margaret">Margaret Johnson</option> <option value="julie">Julie Doodley</option> </select> </form>
用于实时搜索的 HTML 代码
将字符写入输入文本字段后,我们调用函数 。此函数将由事件触发。show_result()onkeyup
看看这个代码示例,它展示了如何为您的网站创建实时搜索:
例复制
<html><head><script>function show_result(str) { if (str.length==0) {
document.getElementById("live_search").innerHTML=""; document.getElementById("live_search").style.border="0px"; return;
} if (window.XMLHttpRequest) {// script for browser version above IE 7 and the other popular browsers (newer browsers)
xmlhttpreq=new XMLHttpRequest();
} else {
// script for the IE 5 and 6 browsers (older versions)
xmlhttpreq=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttpreq.onreadystatechange=function() {//check if server response is ready
if (this.readyState==4 && this.status==200) { document.getElementById("live_search").innerHTML=this.responseText; document.getElementById("live_search").style.border="1px solid #A5ACB2";
}
}
xmlhttpreq.open("GET","/learn/livesearch.php?q="+str,true);
xmlhttpreq.send();
}</script></head><body><form><input type="text" size="30" onkeyup="show_result(this.value)"><div id="live_search"></div></form></body></html>
如果文本输入字段绝对留空(无字符 - ),则函数将清除占位符的内容,并终止函数。str.length==0live_search
如果输入字段中有字符,则函数创建一个 XMLHttpRequest 对象。一旦服务器响应准备就绪,将执行创建的函数。show_result()
HTML表单中的Javascript调用文件livesearch.php在服务器中。其中的脚本搜索与搜索字符串匹配的任何标题。完成后,脚本将返回结果:
例复制
<?php
$xml_doc = new DOMDocument();
$xml_doc->load('persons.xml');
$x=$xml_doc->getElementsByTagName('name');
$q = $_GET['q'];
$result = ''; foreach($x as $node) { if (stripos("{$node->nodeValue}", $q) !== false) {
$result .= "{$node->nodeValue}";
}
} // Set $response to "No records found." in case no hint was found
// or the values of the matching values
if ($result == '')
$result = 'No records found.'; //show the results or "No records found."
echo $result;?>
如果在 AJAX PHP 搜索期间 Javascript 发送任何文本,就会发生这种情况:
XML 文档加载在 XML DOM 对象中。
该脚本循环遍历每个元素以查找所需文本的匹配项。
如果找到一个或多个匹配项,则会返回显示这些匹配项。
如果不存在匹配项,则设置为 。$response"No records found."
创建实时搜索应用程序需要结合 AJAX 和 PHP。
许多用户更喜欢实时搜索而不是传统搜索,因为它的速度和有用的建议。
声明提示:若要转载请务必保留原文链接,申明来源,谢谢合作!
广告位
广告位