PHP beginner's introduction to AJAX real-time search
AJAX can provide users with a more friendly and interactive search experience
In the following example, we will demonstrate a real-time search, and the search results can be obtained while you type the data
Compared with traditional search, real-time search has many advantages:
When typing data, matching results will be displayed
When you continue to typing data, the matching results will be displayed. Filter the results
If there are too few results, delete characters to get a wider range
Please see the following case
First we create a head.xml and the code is as follows
Next we write the php file, the code is as follows:
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; ?>
Note:
If the input box is empty (str.length==0), this function will Clear the contents of the livesearch placeholder and exit the function.
If the input box is not empty, then showResult() will perform the following steps:
Create an XMLHttpRequest object
Create a function that is executed when the server response is ready
Send a request to the file on the server
Please pay attention to the parameter (q) added to the end of the URL (including the content of the input box)
You need to create a new links.xml and put it in the same file In the level directory, the code is as follows:
HTML a 标签 //m.sbmmt.com/tags/tag-a.html HTML br 标签 //m.sbmmt.com/tags/tag-br.html CSS background 属性 //m.sbmmt.com/cssref/css3-pr-background.html CSS border 属性 //m.sbmmt.com/cssref/pr-border.html JavaScript Date 对象 //m.sbmmt.com/jsref/jsref-obj-date.html JavaScript Array 对象 //m.sbmmt.com/jsref/jsref-obj-array.html