📄 php_ajax_livesearch.asp@output=print
字号:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html lang="en-US" xml:lang="en-US" xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>PHP and AJAX Live Search</title>
<link rel="shortcut icon" href="../favicon.ico" type="image/x-icon" />
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
<meta name="Keywords" content="xml,tutorial,html,dhtml,css,xsl,xhtml,javascript,asp,ado,vbscript,dom,sql,colors,soap,php,authoring,programming,training,learning,beginner's guide,primer,lessons,school,howto,reference,examples,samples,source code,tags,demos,tips,links,FAQ,tag list,forms,frames,color table,w3c,cascading style sheets,active server pages,dynamic html,internet,database,development,Web building,Webmaster,html guide" />
<meta name="Description" content="Free HTML XHTML CSS JavaScript DHTML XML DOM XSL XSLT RSS AJAX ASP ADO PHP SQL tutorials, references, examples for web building." />
<meta http-equiv="pragma" content="no-cache" />
<meta http-equiv="cache-control" content="no-cache" />
<script type="text/javascript">
var gaJsHost = (("https:" == document.location.protocol) ? "../../https@ssl./default.htm" : "../../www./default.htm");
document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
</script>
<script type="text/javascript">
var pageTracker = _gat._getTracker("UA-3855518-1");
pageTracker._initData();
pageTracker._trackPageview();
</script>
<script src="livesearch.js" type="text/javascript"></script>
<style type="text/css">
#livesearch
{
margin:0px;
width:194px;
}
#txt1
{
margin:0px;
}
</style>
</head>
<body>
<p>From <b>http://www.w3schools.com</b> (Copyright Refsnes Data)</p>
<h1>PHP and AJAX Live Search</h1>
<a href="php_ajax_responsexml.asp"><img border="0" src="../images/btn_previous.gif" width="100" height="20" alt="Previous" /></a>
<a href="php_ajax_rss_reader.asp"><img border="0" src="../images/btn_next.gif" width="100" height="20" alt="Next" /></a>
<hr />
<p class="intro">AJAX can be used for a more user friendly and interactive
search.</p>
<hr>
<h2>AJAX Live Search</h2>
<p>In the AJAX example below we will demonstrate a live search, where the server
gets search results while the user types.</p>
<p>Live search has many benefits compared to traditional searching:</p>
<ul>
<li>Matching results are shown as you type</li>
<li>Results narrow as you continue typing</li>
<li>If results become too narrow, remove characters to see a broader result</li>
</ul>
<hr>
<h2>Search for a W3Schools page in the Box Below<br />
</h2>
<form>
<input type="text" id="txt1" size="30"
onkeyup="showResult(this.value)">
<div id="livesearch"></div>
</form>
</p>
<p>This example consists of four pages:</p>
<ul>
<li>a simple HTML form</li>
<li>a JavaScript</li>
<li>a
PHP page</li>
<li>an XML document</li>
</ul>
<p>In this example the results are found in an XML document (<a target="_blank" href="links.xml">links.xml</a>). To make this
example small and simple, only eight results are available.</p>
<hr>
<h2>The HTML Form</h2>
<p>This is the HTML page. It contains a simple HTML form, style for the form and
a link to a JavaScript:</p>
<table class="ex" id="table11" border="1" width="100%">
<tr>
<td>
<pre><html>
<head>
<script src="livesearch.js"></script>
<style type="text/css">
#livesearch
{
margin:0px;
width:194px;
}
#txt1
{
margin:0px;
}
</style>
</head>
<body></pre>
<pre><form>
<input type="text" id="txt1" size="30"
onkeyup="showResult(this.value)"></pre>
<pre><div id="livesearch"></div>
</form></pre>
<pre></body>
</html></pre>
</td>
</tr>
</table>
<h2>Example Explained - The HTML Form</h2>
<p>As you can see, the HTML page above contains a simple HTML form with an input field called
"txt1".</p>
<p>The form works like this:</p>
<ol>
<li>An event is triggered when the user presses, and releases a key in the
input field</li>
<li>When the event is triggered, a function called showResult() is executed.
</li>
<li>Below the form is a <div> called "livesearch". This is used as a placeholder for
the return data of the showResult() function.</li>
</ol>
<hr>
<h2>The JavaScript</h2>
<p>The JavaScript code is stored in "livesearch.js" and linked to the HTML
document:</p>
<table class="ex" id="table12" border="1" width="100%">
<tr>
<td>
<pre>var xmlHttp</pre>
<pre>function showResult(str)
{
if (str.length==0)
{
document.getElementById("livesearch").
innerHTML="";
document.getElementById("livesearch").
style.border="0px";
return
}</pre>
<pre>xmlHttp=GetXmlHttpObject()</pre>
<pre>if (xmlHttp==null)
{
alert ("Browser does not support HTTP Request")
return
} </pre>
<pre>var url="livesearch.php"
url=url+"?q="+str
url=url+"&sid="+Math.random()
xmlHttp.onreadystatechange=stateChanged
xmlHttp.open("GET",url,true)
xmlHttp.send(null)
}
function stateChanged()
{
if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
{
document.getElementById("livesearch").
innerHTML=xmlHttp.responseText;
document.getElementById("livesearch").
style.border="1px solid #A5ACB2";
}
}</pre>
<pre>function GetXmlHttpObject()
{
var xmlHttp=null;
try
{
// Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
}
catch (e)
{
// Internet Explorer
try
{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
}
return xmlHttp;
}</pre>
</td>
</tr>
</table>
<h2>Example Explained</h2>
<p>The GetXmlHttpObject function is the same as in the
<a href="php_ajax_suggest.asp">PHP AJAX Suggest</a> chapter.</p>
<p><b>The showResult() Function</b></p>
<p>This function executes every time a character is entered in the input field.</p>
<p>If there is no input in the text field (str.length == 0) the function sets
the return field to empty and removes any border around it.</p>
<p>However, if there is any input in the text field the function
executes the following:</p>
<ol>
<li>Defines the url (filename) to send to the server</li>
<li>Adds a parameter (q) to the url with the content of the input field
</li>
<li>Adds a random number to prevent the server from using a cached file</li>
<li>Calls on the GetXmlHttpObject function to create an XMLHTTP object, and tells the object to execute a function
called stateChanged when a change is triggered</li>
<li>Opens the XMLHTTP object with the given url.</li>
<li>Sends an HTTP request to the server</li>
</ol>
<p><b>The stateChanged() Function</b></p>
<p>This function executes every time the state of the XMLHTTP
object changes.</p>
<p>When the state changes to 4 (or to "complete"), the content of the txtHint
placeholder is filled with the response text, and a border is set around the
return field. </p>
<hr>
<h2>The PHP Page</h2>
<p>The server page called by the JavaScript code is a PHP file called "livesearch.php".</p>
<p>The code in the "livesearch.php" checks the XML document "<a target="_blank" href="links.xml">links.xml</a>".
This document contains titles and URL's of some pages on W3Schools.com.</p>
<p>The code searches the XML file for titles matching the search string and returns the result as HTML:</p>
<table class="ex" id="table10" border="1" width="100%">
<tr>
<td>
<pre><?php
$xmlDoc = new DOMDocument();
$xmlDoc->load("links.xml");</pre>
<pre>$x=$xmlDoc->getElementsByTagName('link');</pre>
<pre>//get the q parameter from URL
$q=$_GET["q"];</pre>
<pre>//lookup all links from the xml file if length of q>0
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)
{
//find a link matching the search text
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>";
}
}
}
}
}</pre>
<pre>// Set output to "no suggestion" if no hint were found
// or to the correct values
if ($hint == "")
{
$response="no suggestion";
}
else
{
$response=$hint;
}</pre>
<pre>//output the response
echo $response;
?></pre>
</td>
</tr>
</table>
<p>If there is any text sent from the JavaScript (strlen($q) > 0) the following
happens:</p>
<ol>
<li>PHP creates an XML DOM object of the "links.xml" file</li>
<li>All "title" elements (nodetypes = 1) are looped through to find a name matching the one sent from the JavaScript</li>
<li>The link containing the correct title is found and set as the
"$response" variable. If more than one match is found, all matches are added
to the variable</li>
<li>If no matches are found the $response variable is set to "no suggestion"</li>
<li>The $result variable is output and sent to the "livesearch" placeholder</li>
</ol>
<hr />
<a href="php_ajax_responsexml.asp"><img border="0" src="../images/btn_previous.gif" width="100" height="20" alt="Previous" /></a>
<a href="php_ajax_rss_reader.asp"><img border="0" src="../images/btn_next.gif" width="100" height="20" alt="Next" /></a>
<p>From <b>http://www.w3schools.com</b> (Copyright Refsnes Data)</p>
</body>
</html>
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -