PHP-Ajax自动完成搜索
PHP-Ajax自动完成搜索 自动完成搜索 当您在字段中输入数据时,“自动完成”搜索框会提供建议。在这里,我们…
PHP-Ajax自动完成搜索
自动完成搜索
当您在字段中输入数据时,“自动完成”搜索框会提供建议。在这里,我们使用xml来调用自动完成建议。下面的示例演示如何与php一起使用自动完成文本框。
索引页
索引页应如下-
<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>
<form>
<h2>Enter Course Name</h2>
<input type="text" size="30" onkeyup="showResult(this.value)">
<div id="livesearch"></div>
<a href="http://www.tutorialspoint.com">More Details </a>
</form>
livesearch.php
它用于从xml文件调用数据,并将结果发送到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="%22%20.%20%24z->item(0)->childNodes->item(0)->nodeValue%20.%20%22" target="_blank">" .
$y->item(0)->childNodes->item(0)->nodeValue . "</a>";
}else {
$hint = $hint . "<br><a href="%22%20.%20%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%24z->item(0)->childNodes->item(0)->nodeValue%20.%20%22" target="_blank">" .
$y->item(0)->childNodes->item(0)->nodeValue . "</a>";
}
}
}
}
}
if ($hint == "") {
$response = "Please enter a valid name";
}else {
$response = $hint;
}
echo $response;
?>
autocomplete.xml
它包含自动完成的数据,并根据标题字段和Url字段由livesearch.php访问
<pages>
<link>
<title>android</title>
<url>http://www.tutorialspoint.com/android/index.htm</url>
<link>
<title>Java</title>
<url>http://www.tutorialspoint.com/java/index.htm</url>
<link>
<title>CSS </title>
<url>http://www.tutorialspoint.com/css/index.htm</url>
<link>
<title>angularjs</title>
<url>http://www.tutorialspoint.com/angularjs/index.htm </url>
<link>
<title>hadoop</title>
<url>http://www.tutorialspoint.com/hadoop/index.htm </url>
<link>
<title>swift</title>
<url>http://www.tutorialspoint.com/swift/index.htm </url>
<link>
<title>ruby</title>
<url>http://www.tutorialspoint.com/ruby/index.htm </url>
<link>
<title>nodejs</title>
<url>http://www.tutorialspoint.com/nodejs/index.htm </url>
</pages>
它将产生以下结果-

类别:PHP 技巧、
本文收集自互联网,转载请注明来源。
如有侵权,请联系 wper_net@163.com 删除。
还没有任何评论,赶紧来占个楼吧!