Use PHP + JavaScript to create an Ajax search window

Source: Internet
Author: User
Tags echo command
I. Introduction

Search is a widely used function in the web world. With the development of web technology, in order to better meet customers' needs, conventional search engines have begun to "Open the door" to more unconventional methods ". In this regard, Yahoo! Take the lead to provide its y! Q service. This new service allows you to search for any web page, provided that the author of this page must be included in their web page. It is the service technology that presents the relevant search results to the reader, so as to display more information to the reader without having to leave their current page.

Yahoo! Y! Q service is indeed a great idea, but its appearance has also been criticized. Why? First, it requires the client to use Yahoo! And you must add a <form/> element to meet Yahoo! . For many website authors, too much effort is required to provide this service. In addition, after all these conditions are met, the search result is Yahoo! Style display damages the appearance of your website.

Fortunately, Yahoo! It is not the only search engine that provides the "provide search results from your website" service. MSN Search also provides a similar service, in addition to allowing Web developers to control the appearance. This capability comes from the RSS version of the search result provided by MSN Search, making it possible to subscribe to a specific search or add the result to your page using Ajax.

Although Google has already taken the lead in implementing this new "search from your site" technology, at the time of writing this article, google blogsearch beta related to Google can also provide returned results in RSS or atom format.

  Ii. Server Components

When you use MSN Search to perform a search, you will see an orange XML image at the bottom of the result page. Clicking 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 code to retrieve remote feeds. For the search window in this article, you will use PHP to search for the feed. The URL from the server application request information looks as follows:

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

Set the required header in the first two rows so that the browser can process the data correctly (in XML format, and the results are not buffered ). The next line of code uses the isset () function to determine whether the search key exists in the query string.

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 "Magic quotes" is enabled in the PHP configuration (supported by default), a slash (for example,) will be used for any quotation marks that reach the PHP engine, /"search query. The stripslashes () function is responsible for deleting these symbols, leaving only "search query ". After deleting the slash, go to the urlencode () function, which is used to encode characters for query strings. Spaces, quotation marks, and "&" are all encoded.

Note that if the search term cannot be "filtered" by these functions, the MSN server returns a code 400-"Bad request ".

When you have prepared a conversion search term, it is included in the URL and stored in the $ URL variable. Finally, the file_get_contents () function is used to open a remote file, read its content, return it to the $ XML variable in the form of a string, and print it to the page using the echo command.

  3. Client components

The client code of the search window (widget) in this article is created based on a static object msnwebsearch-it is defined as an object without any attributes (now:

VaR msnwebsearch = {};

This object is used to execute a search in the onclick event of an htmlelement:

<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 HTML containing the data. The first method is drawresultbox (), which is used to draw HTML. The HTML generated by this method is as follows:

<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 consists of a header and a result column (see figure 1 ). The header tells the user that this new search window contains results from an MSN Search. It also contains an "X" used to close the small window. The result Bar contains block-style links. A new window is displayed when you click these links.


Figure 1. The result box consists of a header and a result column.

Iv. User Interface for drawing results

The code for generating this HTML is quite long, because all the elements are generated using the DOM method. The drawresultbox () method accepts a parameter (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 ("");

The preceding Code creates HTML elements using the createelement () method. After creating these elements, you can start to assign them attributes. The two final elements above are acloselink and divheading:

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

Complete the link to close the result box in the first four rows. The method close () becomes the processor of the linked onclick event. The following lines of code fill the header with text and closed Links <DIV/>.

When the 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 display a message indicating that the data is being loaded (this method 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 and loads a message and adds it to divresultspane. It also assigns the class name to divresultspane.


Figure 2. prompt the user that the data is being loaded

After these elements are completed, add them to the divsearchbox element:

Divsearchbox. classname = "ajaxwebsearchbox ";
Divsearchbox. appendchild (divheading );
Divsearchbox. appendchild (divresultspane );
Document. Body. appendchild (divsearchbox );

This Code adds divheading and divresultspane elements to the search window and adds the search window to the page.

The last step in drawresultbox () is to determine the location 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 ("");
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 a msnwebsearch object is created in this way, the divsearchbox must be returned to its caller for other operations. You can guess that the position () method is used to place the search box. It accepts two parameters: the event object passed to drawresultbox () and the divsearchbox element:

Msnwebsearch. Position = function (E, divsearchbox ){
VaR x = E. clientx + document.doc umentelement. scrollleft;
Var y = E. clienty + document.doc umentelement. scrolltop;
Divsearchbox. style. Left = x + "PX ";
Divsearchbox. style. Top = Y + "PX ";
};

The first two lines of code get the left and top positions, used to place the search result box. Two types of information are required for this operation. The first is the X and Y coordinates of the mouse (the information is stored in the clientx and clienty attributes ).

However, these coordinates are not enough to correctly locate the result box, because the clientx and clienty attributes return the cursor position relative to the client area of the browser window, rather than the actual coordinates on 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 determine the position in the box where the user clicks the mouse.
  5. Display Results

The populateresults () method fills the result bar with search results. It accepts two parameters: the element containing the result and an xparser object (xparser is a javascript-based RSS reader that can be freely downloaded from www.wdonline.com/javascript/xparser ):

Msnwebsearch. populateresults = function (divresultspane, oparser ){
VaR ofragment = Document. createdocumentfragment ();

Divresultspane. removechild (divresultspane. firstchild );

This method uses the DOM method to generate <A/> elements programmatically. In this way, these elements are added to a document segment created in the first line. Delete the <DIV/> element that is being loaded in drawresultbox () in the next row.

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 ("");
Aresultlink. href = oitem. Link. value;
Aresultlink. classname = "ajaxwebsearchlink ";
Aresultlink.tar get = "_ new ";
Aresultlink. appendchild (document. createtextnode (oitem. Title. Value ));

Ofragment. appendchild (aresultlink );
}

This code traverses each item of feedback, generates a link from the data, and adds the <A/> element to the end of the document segment.

When you exit the loop, this document segment is added to divresultspane to display the search results:

Divresultspane. appendchild (ofragment );

  6. Close the result box

To close the search result box, the close () method is provided for the msnwebsearch object. The close () method is used to process the onclick event of The Link (close 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 is deleted from this document. Therefore, you need to retrieve the divsearchbox element. The first line of code completes this task by retrieving the parent node of the element's parent node. Because close () is responsible for processing the onclick event, this references this link. The next line deletes the divsearchbox element from the document. In the last line, false is returned, which forces the browser not to follow the default behavior of a link (to the location marked in the href attribute ).

  7. Build a search interface

The last method of the msnwebsearch object is search (), which provides an interface for executing a search. You can use an onclick event of an element to call 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 event e to it. Encode the URL in the next line for proper conversion. This URL is passed to the xparser constructor to create a new analyzer. When the search feedback is loaded and the result is filled in the search box, the analyzer's onload event processor calls the populateresult () method.
Of course, one reason to build this search box is to make it more suitable for the appearance of your site.

  8. Customize the Web search box

With CSS, you can easily customize the search box for your existing website and make any redesign easier.

The CSS class to be discussed first is ajaxwebsearchbox (which implements the search box ). To determine the position of the search box, it must have an absolute position:

. Ajaxwebsearchbox
{
Position: absolute;
Background-color: # 0d1e4a;
Width: 500px;
Padding: 1px;
}

Here, the absolute position is the only requirement. All other attributes are optional based on your taste. In this example, the box has a micro-blue background, a 500 pixel width, and one pixel fill on each side. This fill leads to a boundary of 1 pixel width surrounding the content of the box.

The next class is ajaxwebsearchheading, which contains the header text and closed link of the box. In order to put the closed link in the upper right corner, it uses an absolute position. For this reason, it requires that ajaxwebsearchheading 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 attribute is the position attribute. Other attributes help to give the element a nice look. The background color is light blue, while the text is white, 14 pixels high and tahoma font. The height of the element is 21 pixels and is filled with borders on the top and left.

As described above, the closed link is absolutely located:

A. ajaxwebsearchcloselink
{
Position: absolute;
Right: 5px;
Top: 3px;
Text-Decoration: none;
Color: white;
}
A: hover. ajaxwebsearchcloselink
{
Color: red;
}

This element is placed at 5 pixels to the right and 3 pixels to the top (the element is placed in the upper right corner ). This link is not decorated with any text and the color is white. When the user's mouse stops at the link, the text turns red.

Note that the accessed or active "fake" class is not used here. This is because the window always ignores the href attribute of the Link (it has returned false in its event processor ). Therefore, the link is never truly active or accessed.

Then, the ajaxwebsearchresults class makes the result bar style as follows:

. Ajaxwebsearchresults
{
Background-color: # d3e5fa;
Padding: 5px;
}

CSS attributes are not required for this element. The existing attribute is only used to define the result bar and make it easier to read. The background color is light blue with 5 pixels filled around the edge. Of course, you can customize the message loading style:

. 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 preceding example. In this example, the text is placed in the center of the <DIV/> element, and a bold blue font is given, with 14 pixels High.

The final element you need To stylized is the result link. These links have a class named ajaxwebsearchlink:

A. ajaxwebsearchlink
{
Font: 12px tahoma;
Padding: 2px;
Display: block;
Color: # 0a246a;
}
A: hover. ajaxwebsearchlink
{
Color: white;
Background-color: # abstrac5;
}
A: visited. ajaxwebsearchlink
{
Color: Purple;
}

The only property required is the display property (set to block ). This enables each link to be displayed on its own line. The padding space is about two pixels wide, separating links to make them easier to read. The font name is tahoma and is 12 pixels High. Their colors are dark blue, in contrast to the light blue background of ajaxwebsearchresults.

When you move the mouse over these links, the background color is set to blue, and the text color changes to white.

The "fake" class accessed in the last rule of the previous code is set. This is to give users an indication that user interfaces have been used. By setting the accessed "fake" class to display a purple color, you can know the link they have accessed, thus saving their time-no longer having to access a page that they might not want to see.

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

  9. Implement the Web search box

It is very easy to implement this search box. First, you must upload the Websearch. php file to your web server (of course, you must install PHP ). Then, you need an HTML document to reference all the components. Msnwebsearch objects depend on the xparser class, which depends on the zxml Library (which can be downloaded from www.nczonline.net/downloads ). You must reference the following files:

<! Doctype HTML public "-// W3C // dtd xhtml 1.0 transitional // en"
Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd>
<Html xml: lang = "en" lang = "en" xmlns = "http://www.w3.org/1999/xhtml">
<Head>
<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>
</Head> <body>
</Body>
</Html>

To perform a search, set the msnwebsearch. Search () method to The onclick processor of the element:

<! Doctype HTML public "-// W3C // dtd xhtml 1.0 transitional // en"
Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd>
<Html xml: lang = "en" lang = "en" xmlns = "http://www.w3.org/1999/xhtml">
<Head>
<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>
</Head> <body>
<A href = "#" onclick = 'msnwebsearch. Search (event, "/" professional ajax /"");
Return false; '> search for "professional Ajax" </a>
<Br/>
<A href = "#" onclick = 'msnwebsearch. Search (event, "professional Ajax ");
Return false; '> Search for professional Ajax </a>
</Body>
</Html>

The first new link executes a search for the exact phrase "professional Ajax", and the second link searches for each word. Note that the onclick event returns false-This forces the browser to ignore the href attribute. Click these links to draw the search box at the cursor position, and your search results will be displayed here.

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.