PHP 和 AJAX Live Search

AJAX can provide a more friendly, more interactive search experience for users.

AJAX Live Search

In the AJAX example below we will demonstrate a real-time search.

Compared with the traditional real-time search search, it has many advantages:

  • When the data type, the results are displayed matching
  • When continue typing data, filter results
  • If too few results, you can delete the character to get a wider range

In the following pages the search text box W3School

This embodiment comprises four elements:

  • Simple HTML form
  • JavaScript
  • PHP page
  • XML documents

In this case, the results look in an XML document (links.xml) in. To make the example small and simple, we only offer 8 results.

HTML form

This is the HTML page. It contains a simple HTML form, CSS styles for this form, and a link to a JavaScript:

<html>
<head>
<script src="livesearch.js"></script> 
<style type="text/css"> 
#livesearch
  { 
  margin:0px;
  width:194px; 
  }
#txt1
  { 
  margin:0px;
  } 
</style>
</head>
<body>

<form>
<input type="text" id="txt1" size="30"
onkeyup="showResult(this.value)">

<div id="livesearch"></div>
</form>

</body>
</html>

Example explained - HTML Forms

As you can see, HTML page contains a simple HTML form, which is a text box entitled "txt1".

Forms works like this:

  1. When the user keys in a text box, and the button is released, it will trigger an event
  2. When an event is triggered, it will perform the function named showResult () of
  3. The following is a form called "livesearch" the <div> element. It serves as the showResult () returns the data placeholders

JavaScript

JavaScript code is stored in connection with the HTML document "livesearch.js" in:

var xmlHttp

function showResult(str)
{
if (str.length==0)
 { 
 document.getElementById("livesearch").
 innerHTML="";
 document.getElementById("livesearch").
 style.border="0px";
 return
 }

xmlHttp=GetXmlHttpObject()

if (xmlHttp==null)
 {
 alert ("Browser does not support HTTP Request")
 return
 }

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";
 } 
}

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;
}

Example explained:

GetXmlHttpObject with PHP and AJAX request the same example.

showResult () function

The function whenever a character input text box will be executed once.

If you do not enter the text field (str.length == 0), the function returns the field to empty and remove any borders around.

However, if there is an input text field, the function execution:

  1. Send to a server's url (filename)
  2. Input box with the contents of the parameter (q) is added to the url
  3. Add a random number to prevent the server uses cache files
  4. GetXmlHttpObject function call to create the XMLHTTP object, and inform the implementation of this function is a function called stateChanged when triggered a change
  5. Given the XMLHTTP object to open url
  6. Send HTTP requests to the server

stateChanged () function

Whenever the state of the XMLHTTP object is changed, the function will be executed.

When the state is changed to 4 (or "complete"), will be used to populate the response text content txtHint placeholders, and return is provided a frame around the field.

PHP page

Server page called by the JavaScript code is called "livesearch.php" PHP file.

"Livesearch.php" the code checks that XML documents "links.xml". Title and URL on some pages of the document w3school.com.cn.

This code searches the XML file title match the search string, and returns the result as HTML:

<?php
$xmlDoc = new DOMDocument();
$xmlDoc->load("links.xml");

$x=$xmlDoc->getElementsByTagName('link');

//get the q parameter from URL
$q=$_GET["q"];

//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>";
    }
   }
  }
 }
}

// Set output to "no suggestion" if no hint were found
// or to the correct values
if ($hint == "")
 {
 $response="no suggestion";
 }
else
 {
 $response=$hint;
 }
 
//output the response
echo $response;
?>

Example explained:

If any text sent from JavaScript (strlen ($ q)> 0), occur:

  1. PHP create "links.xml" file of a XML DOM object
  2. Through all "title" element (nodetypes = 1), in order to find the name of the transmitted data matching JavaScript
  3. Find the link contains the correct title and set to "$ response" variable. If it finds more than one match, all matches will be added to the variable
  4. If no match is found, put the $ response variable is set to "no suggestion"
  5. $ Result is sent to the "livesearch" placeholder output

Guess you like

Origin www.cnblogs.com/fewfwf/p/11829665.html