Auto Complete Search là gì?
AutoComplete search box cung cấp các gợi ý khi bạn nhập dữ liệu vào trường. Tại đây, chúng ta sử dụng XML để gọi các gợi ý Autocomplete này. Ví dụ dưới minh họa cách sử dụng Autocomplete text box bởi sử dụng với PHP.
Index page
Index page nên là như sau:
<html>
<head>
<style>
div {
width:240px;
color:green;
}
</style>
<script>
function showResult(str) {
if (str.length==0) {
document.getElementById("livesearch").innerHTML="";
document.getElementById("livesearch").style.border="0px";
return;
}
if (window.XMLHttpRequest) {
xmlhttp=new XMLHttpRequest();
}
else
{
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();
}
</script>
</head>
<body>
<form>
<h2>Nhập tên khóa học</h2>
<input type="text" size="30" onkeyup="showResult(this.value)">
<div id="livesearch"></div>
<a href="https://lib24.vn">Chi tiết khóa học </a>
</form>
</body>
</html>
Tệp livesearch.php
Tệp này được sử dụng để gọi data từ xml file và nó sẽ gửi kết quả tới trình duyệt web.
<?php
$xmlDoc=new DOMDocument();
$xmlDoc->load("autocomplete.xml");
$x=$xmlDoc->getElementsByTagName('link');
$q=$_GET["q"];
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="<a href='" . $z->item(0)->childNodes->item(0)->nodeValue . "' target='_blank'>" .
$y->item(0)->childNodes->item(0)->nodeValue . "</a>";
}
else
{
$hint=$hint . "<br/><a href='" .
$z->item(0)->childNodes->item(0)->nodeValue . "' target='_blank'>" .
$y->item(0)->childNodes->item(0)->nodeValue . "</a>";
}
}
}
}
}
if ($hint=="") {
$response="Mời bạn nhập một tên hợp lệ";
}
else
{
$response=$hint;
}
echo $response;
?>
Tệp autocomplete.xml
File này chứa auto complete data và được truy cập bởi livesearch.php dựa trên trường title và url.
<pages>
<link>
<title>Toán</title>
<url>https://lib24.vn/toan</url>
</link>
<link>
<title>Ngoại Ngữ</title>
<url>https://lib24.vn/tieng-anh</url>
</link>
<link>
<title>Ngữ Văn </title>
<url>https://lib24.vn/ngu-van</url>
</link>
</pages>
Lưu chương trình trên trong một file có tên là test.php trong htdocs, sau đó mở trình duyệt và gõ địa chỉ http://localhost:8080/test.php sẽ cho kết quả:
Được cập nhật: 9 giờ trước (1:04:36) | Lượt xem: 431