Using Php+javascript to create Ajax search Windows

Source: Internet
Author: User
Tags final functions header implement php file first row urlencode xmlns

   first, the introduction

One of the most widely used features in the Web world is search. With the development of web technology, in order to better meet customer demand, the regular search engine began to more unconventional way "open the door." In this respect, Yahoo! is the first to provide its Y! Q Service. This new service enables you to search any Web page, provided that the author of the page must be included in their web page. It is the service technology that enables you to present the relevant search results to the reader so that you can show more information to the reader without leaving their current page.

Yahoo! 's Y! Q Service is indeed a great idea, but it has also been criticized for its emergence. Why? First, it requires the client to use Yahoo! JavaScript and you must add a <form/> element to satisfy the Yahoo! search requirements. For many web site authors, the provision of this service requires too much effort. And, after all these conditions are met, the search results will be displayed in Yahoo! style, thereby damaging the appearance of the user's site.

Fortunately, Yahoo! is not the only search engine that offers "search results from your site" service. MSN Search also provides a similar service, except that it enables Web developers to control the look and feel. This ability comes from the RSS version of MSN Search that provides its results, which makes it possible to subscribe to a specific search or use Ajax methods to add the results to your page.

Although Google has pioneered this new "Search from your site" technology, Google-related Google Blogsearch Beta has been able to provide returns in RSS or Atom format at the time of this article.

   second, server-side components

When searching using MSN Search, you will see an orange-colored XML image appear at the bottom of the resulting page. Clicking on this image will take you to a new page and provide you with a URL to subscribe to the search.

In this way, you can write server-side code to retrieve remote feeds. For the Search window in this article, you will use PHP to retrieve the search feed. The URL from the server application request information looks like the following:

Websearch.php?search=[searchterm]
The query string has only one variable: "search"; Therefore, the application should look for this query item. On the server side, you need to create a page to "pull" this data:

<?php
Header ("Content-type:text/xml");
Header ("Cache-control:no-cache"); if (Isset ($_get["search"))
{
$searchTerm = UrlEncode (stripslashes ($_get["search"));
$url = "http://search.msn.com/results.aspx?q= $searchTerm &format=rss";
$xml = file_get_contents ($url);
Echo $xml;
}
? >
The first two lines set the required headers so that the browser can handle the data correctly (in XML form and without buffering the results). The next line of code uses the Isset () function to determine whether the search key exists in the query string.

In order to send a suitable request to a remote host, the search term should be "filtered" by many functions. First, it is passed to the stripslashes () function. If the "Magic quotes" (which is supported by default) is started in the PHP configuration, any quotes that arrive at the PHP engine are automatically taken off using a slash (such as, "Search Query\"). The Stripslashes () function deletes these symbols and leaves only "search query". After the slash is removed, go to the UrlEncode () function, which is responsible for encoding characters for the query string. Symbols such as spaces, quotes, "&" are encoded.

Note If search terms do not "filter" through these functions, the MSN Server will return a code 400-"bad Request".

When the search term is ready for conversion, it is included in the URL and stored in the $url variable. Finally, the file_get_contents () function opens the remote file, reads its contents, returns it to the $xml variable as a string, and then prints it to the page using the echo command.

   third, the client component

The client code for the Search window (Widget) in this article is created based on a static object Msnwebsearch-it is defined as an object that does not have any attributes (now):

var msnwebsearch ={};
This object is used in a HtmlElement onclick event to perform a search:

<a Href= "#"
onclick= ' Msnwebsearch.search (event, "Professional Ajax"); return false; ' >
Professional Ajax
</a>
This Msnwebsearch object provides several methods for obtaining search results and is responsible for drawing and placing the HTML that contains the data. The first method is Drawresultbox (), which is responsible for drawing HTML. The HTML that this method forms is shown below:

<divclass= "Ajaxwebsearchbox" >
<div class= "ajaxwebsearchheading" >msn Search Results
<a Class= "Ajaxwebsearchcloselink" href= "#" >x </a>
</div>
<div class= "Ajaxwebsearchresults"
<a Class= "Ajaxwebsearchlink" target= "_new"
<a Class= "Ajaxwebsearchlink" target= "_new"
</div>
</div>
The result box is divided into two parts: a header and a result bar (see Figure 1). The head tells the user that the new search window contains results from an MSN Search. It also contains an "X" to close the small window. The result bar contains a block-style link, and a new window will be clicked when you click on the link.


Figure 1. The result box is divided into two parts: a head and a result bar

   Iv. user interface for rendering results

The code that generates this HTML is rather long because the elements are generated using the DOM method. The Drawresultbox () method accepts an argument (an event object):

Msnwebsearch.drawresultbox = function (e) {
var divsearchbox= document.createelement ("div");
var divheading = document.createelement ("div");
var Divresultspane = document.createelement ("div");
var acloselink = document.createelement ("a");
The preceding code creates HTML elements through the createelement () method. Once you have created these elements, you can begin to give them attributes. The two elements of the above completion (end) are Acloselink and divheading respectively:

Acloselink.href = "#";
Acloselink.classname = "Ajaxwebsearchcloselink";
Acloselink.onclick = This.close;
Acloselink.appendchild (document.createTextNode ("X"));
Divheading.classname = "ajaxwebsearchheading";
Divheading.appendchild (document.createTextNode ("MSN Search Results"));
Divheading.appendchild (Acloselink);
The first four lines complete the link to close the result box. Where the method close () becomes the processor of the linked onclick event. The next few lines of code are responsible for using text and closing the link to fill the header's <div/>.

When this result box is drawn to the page, no response from a server application has been received. To show the user what has happened, you can show the user a message that the data is being loaded (this way is more friendly) (see Figure 2). To do this, create another element and add it to the Divresultspane element:

var divloading = document.createelement ("div");
Divloading.appendchild (document.createTextNode ("Loading Search Feed"));

Divresultspane.classname = "Ajaxwebsearchresults";
Divresultspane.appendchild (divloading);
This code creates the load message and adds it to the Divresultspane, while also assigning the class name to Divresultspane.


Figure 2. Prompting the user for data being loaded


After these elements are complete, the rest is to add them to the Divsearchbox element:

Divsearchbox.classname = "Ajaxwebsearchbox";
Divsearchbox.appendchild (divheading);
Divsearchbox.appendchild (Divresultspane);
Document.body.appendChild (Divsearchbox);
This code is responsible for adding the divheading and Divresultspane elements to the search window and adding the Search window to the page.

The final step in Drawresultbox () is to determine the position of the newly drawn small box and return Divsearchbox to its caller:

Msnwebsearch.drawresultbox = function (e) {
var divsearchbox= document.createelement ("div");
var divheading = document.createelement ("div");
var Divresultspane = document.createelement ("div");
var acloselink = document.createelement ("a");
Acloselink.href = "#";
Acloselink.classname = "Ajaxwebsearchcloselink";
Acloselink.onclick = This.close;
Acloselink.appendchild (document.createTextNode ("X"));
Divheading.classname = "ajaxwebsearchheading";
Divheading.appendchild (document.createTextNode ("MSN Search Results"));
Divheading.appendchild (Acloselink);
var divloading = document.createelement ("div");
Divloading.appendchild (document.createTextNode ("Loading Search Feed"));
Divresultspane.classname = "Ajaxwebsearchresults";
Divresultspane.appendchild (divloading);
Divsearchbox.classname = "Ajaxwebsearchbox";
Divsearchbox.appendchild (divheading);
Divsearchbox.appendchild (Divresultspane);
Document.body.appendChild (Divsearchbox);
This.position (E, divsearchbox);
return divsearchbox;
};
After the Msnwebsearch object is established in this way, the Divsearchbox must be returned to its caller for other operations. You can already guess that the position () method is responsible for placing the search box. It accepts two parameters: the event object and the Divsearchbox element passed to Drawresultbox ():

Msnwebsearch.position = function (e, divsearchbox) {
var x = E.clientx + document.documentElement.scrollLeft;
var y = e.clienty + document.documentElement.scrollTop;
DivSearchBox.style.left = x + "px";
DivSearchBox.style.top = y + "px";
};
The first two lines of code get the left and top positions to place the search results box. Performing this operation requires the use of two types of information. The first is the x and y coordinates of the mouse (which are stored in the Clientx and Clienty properties).

However, these coordinates are not sufficient to properly position the result box because the Clientx and Clienty properties return the mouse position relative to the client area of the browser window, not the actual coordinates in the page. With this in mind, we can use the scrollleft and scrolltop attributes of the document element. After calculating the final coordinates, you can finally determine where the user clicks the mouse box.

   v. Display of results

The Populateresults () method is responsible for populating the results column with search results. It takes two parameters: the element that contains the result and a Xparser object (Xparser is a JavaScript based RSS reader, free to download from www.wdonline.com/javascript/xparser/):

Msnwebsearch.populateresults = function (divresultspane,oparser) {
var ofragment = document.createdocumentfragment ();

Divresultspane.removechild (Divresultspane.firstchild);
This method generates <a/> elements programmatically and through the DOM method, so that these elements are added to a document fragment that is created in the first row. The next line deletes the loaded <div/> element that is added in Drawresultbox ().

The next step is to create this link:

for (var i = 0; I oParser.items.length i++) {
var oitem = oparser.items[i];

var aresultlink = document.createelement ("a");
Aresultlink.href = OItem.link.value;
Aresultlink.classname = "Ajaxwebsearchlink";
Aresultlink.target = "_new";
Aresultlink.appendchild (document.createTextNode (OItem.title.value));

Ofragment.appendchild (Aresultlink);
}
This code iterates through the individual items of the feedback, and the data is generated by the link and the <a/> element is added to the document fragment at the end.

When you exit the loop, the document fragment is added to Divresultspane to display the search results:

Divresultspane.appendchild (ofragment);
   Close the result box

To turn off the search results box, the Msnwebsearch object provides the close () method. The close () method handles the OnClick event for the link (closes the small box):

Msnwebsearch.close = function () {
var divsearchbox = This.parentNode.parentNode;
Document.body.removeChild (Divsearchbox);

return false;
};
The search box is not actually closed; in fact, it was removed from the document. To do this, you need to retrieve the Divsearchbox element. The first line of code accomplishes this task-by retrieving the parent node of this element's parent node implementation. Because close () is responsible for handling the onclick event, this refers to this link. The next line deletes the Divsearchbox element from the document. The last line, returns false, forcing the browser not to follow the default behavior of a link (go to the location labeled in the href attribute).

   Vii. Build the Search interface

The last method of the Msnwebsearch object is search (), which provides an interface to perform a search. You can use an element's OnClick event to invoke search (). It accepts two methods: an Event object and a search term:

Msnwebsearch.search = function (e,ssearchterm) {
var divsearchbox = This.drawresultbox (e);
var url = encodeURI ("websearch.php?search=" + ssearchterm);
var oparser = new Xparser (URL);
Oparser.onload = function () {
Msnwebsearch.populateresults (Divsearchbox.childnodes[1],oparser);
};
};
The first line calls the Drawresultbox () method and passes the event E to it. The next line encodes the URL to implement the appropriate conversion. This URL is passed to the Xparser constructor to create a new parser. When the search feedback completes loading and the search box is populated with results, the OnLoad event handler for the parser invokes the Populateresult () method.
Of course, one of the reasons to build this search box is to make it more appropriate for the look of your own site.

   Eight, custom web search box

With CSS, you can easily customize your search box for your existing site and make it easy for any future redesign.

The first CSS class to discuss is the Ajaxwebsearchbox (the class implements the search box). Because the search box has to be positioned, it must have an absolute position:

. Ajaxwebsearchbox
{
Position:absolute;
Background-color: #0d1e4a;
width:500px;
padding:1px;
}
In this case, absolute position is the only requirement. All the other attributes are optional based on your taste. In this example, the box has a bluish background, a 500-pixel width, and a 1-pixel padding on four sides. This padding causes the contents of the box to be around 1 pixel wide boundaries.

The next class is Ajaxwebsearchheading, which contains the header text and closing links for the box. To put the closing link in the upper-right corner, it uses an absolute position. For this reason, it requires ajaxwebsearchheading to use a relative position:

. ajaxwebsearchheading
{
position:relative;
Background-color: #1162cc;
Font:bold 14px Tahoma;
height:21px;
Color:white;
padding:3px 0px 0px 2px;
}
Here, the only required property is the Position property. Other properties help give the element a nice look. The background color is light blue, and the text part is white, 14 pixels high and is Tahoma font. The height of the element is 21 pixels and is populated at the top and left edges.

As mentioned earlier, the location of the close link is absolute:

A.ajaxwebsearchcloselink
{
Position:absolute;
right:5px;
top:3px;
Text-decoration:none;
Color:white;
}
A:hover.ajaxwebsearchcloselink
{
color:red;
}
The element is placed 5 pixels to the right and 3 pixels from the top (the element is positioned in the upper-right corner). This link does not have any text decoration and the color is white. The text color turns red when the user's mouse stops on the link.

Note that there is no "fake" class that has been accessed or active. This is because the window always ignores the href attribute of the link (it has returned false in its event handler). Therefore, the link is never really active or accessed.

The Ajaxwebsearchresults class then makes the result bar style as follows:

. ajaxwebsearchresults
{
Background-color: #d3e5fa;
padding:5px;
}
This element does not require the use of CSS properties. Existing properties are used only to define the result bar and make it easier to read. The background color is a light blue and has a 5-pixel fill around the edge. Of course, you can customize the style of loading messages:

. Ajaxwebsearchresults Div
{
Text-align:center;
Font:bold 14px Tahoma;
Color: #0a246a;
}
This element does not have a class name, but you can still control its style by using the parent child flag shown in the previous example. This example places the text in the middle of the <div/> element and gives it a bold blue font, with a height of 14 pixels.

The last element you need to style is the result link. These links have a class called Ajaxwebsearchlink:

A.ajaxwebsearchlink
{
font:12px Tahoma;
padding:2px;
Display:block;
Color: #0a246a;
}
A:hover.ajaxwebsearchlink
{
Color:white;
Background-color: #316ac5;
}
A:visited.ajaxwebsearchlink
{
Color:purple;
}
The only required property is the display property (which is set to block). This allows each link to be displayed on its own line. The padding space is about two pixels wide, separating the links and making them easier to read. The font name is Tahoma and has a height of 12 pixels. Their color is dark blue, contrasted with the light blue background of the ajaxwebsearchresults.

When the user moves the mouse over these links, the background color is set to blue, and the text color is changed to white.

The "fake" class accessed in the last rule of the preceding code is set. This is to give users a hint of user interface-they have already been used. By setting the visited "Fake" class to show a purple color, users can know that they have visited the link and thus save their time-no more access to a page that they might not want to read.

Now, let's take a look at how to implement the search box.

   implementation of the Web search search box

It is easy to implement this search box. First, you must upload the websearch.php file to your Web server (and, of course, PHP must be installed). Then, you need an HTML document to refer to all the components. The Msnwebsearch object relies on the Xparser class, which is also dependent on the Zxml library (which can be downloaded from www.nczonline.net/downloads/). You must refer to the following files:

! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en"
"Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd" >
<meta http-equiv= "Content-type" content= "text/html; Charset=utf-8 "/>
<title> Ajax websearch </title>
<link rel= "stylesheet" type= "Text/css" href= "css/websearch.css"/>
<script type= "Text/javascript" src= "js/zxml.js" > </script>
<script type= "Text/javascript" src= "js/xparser.js" > </script>
<script type= "Text/javascript" src= "js/websearch.js" > </script>
</body>
In order to perform a search, you should set the Msnwebsearch.search () method to the element's OnClick processor:

! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en"
"Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd" >
<meta http-equiv= "Content-type" content= "text/html; Charset=utf-8 "/>
<title> Ajax websearch </title>
<link rel= "stylesheet" type= "Text/css" href= "css/websearch.css"/>
<script type= "Text/javascript" src= "js/zxml.js" > </script>
<script type= "Text/javascript" src= "js/xparser.js" > </script>
<script type= "Text/javascript" src= "js/websearch.js" > </script>
<a Href= "#" onclick= ' Msnwebsearch.search (event, "\" Professional ajax\ ");
return false; ' >search for "Professional Ajax" </a>
<BR/><br/><br/><BR/>
<a Href= "#" onclick= ' Msnwebsearch.search (event, "Professional Ajax");
return false; ' >search for Professional Ajax </a>
</body>
The first new link executes a search for the exact phrase "Professional Ajax," and the second link searches for each of these words. Also note that false-is returned in the OnClick event, which forces the browser to ignore the href attribute. Clicking on these links will draw the search box at the cursor location and show your search results here.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.