This article mainly introduces the real-time search prompt function implemented by PHP+JS, which involves PHP combined with ajax real-time transmission of data and string traversal and matching related operation skills. Friends in need can refer to it. I hope it can help everyone.
The rendering is as follows:
The code is as follows:
HTML code: (This code is implemented in two ways, one is Jquery, A kind of native JS)
<html> <head> <script src="/DelphiRequest/search/js/jquery.js"></script> <script> /*用原生js实现 // 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(); // } */ //用jquery实现 function showResult(str){ $.ajax({ type: "GET", url : "livesearch.php", datatype : 'json', data: {'q':str} , success :function (data) { document.getElementById("livesearch").innerHTML=data; document.getElementById("livesearch").style.border="1px solid #A5ACB2"; } }) } </script> </head> <body> <form> <input type="text" size="30" onkeyup="showResult(this.value)"> <p id="livesearch"></p> </form> </body> </html>
The PHP code is as follows: (PHP can not only consider using arrays directly, but also directly query the database to obtain the database content. This code uses Array. )
<?php $provinces=array("beijing","tianjin","shanghai","chongqing","hebei","henan","heilongjiang","jilin","changchun", "shandong","anhui","shanxi","guangzhou","yunnan","hainan","xizang","qinghai","fujian","guizhou","jiangsu", "zhejiang","guangzhou","yunan","hainan","xizang","neimenggu","sichuan","gansu","ningxia","xianggang","aomen"); $tmp=$_GET['q']; $val=array(); $k=0; if (strlen($tmp)>0) { for($i=0;$i<31;$i++){ if(strpos($provinces[$i],$tmp)!==false){ //传递值给val $val[$k]=$provinces[$i]; //下标增加 $k=$k+1; } } //遍历val数组 for($j=0;$j<count($val);$j++) { echo $val[$j]; echo "<br>"; } } ?>
Related recommendations:
## PHP search prompt: search-suggest
php+jquery Example of implementing search prompt function
The above is the detailed content of PHP and JS realize search prompt function code sharing. For more information, please follow other related articles on the PHP Chinese website!