Create a blog with no refreshing search through AJAX

Source: Internet
Author: User

If you are not familiar with AJAX, take a look at this tutorial:Top AJAX experience.

Nowadays, blogs are very popular. I believe that anyone who needs to spend a little time surfing the internet will have a blog here or there. Some friends with certain abilities may prefer to download a blog program to set up their own blog, rather than using the services provided by some blog websites. Most blog programs use the search function to submit query keywords to the search page, generate search results in the background, and then present the results to users. This process wastes some bandwidth, for example, the sidebar of a blog. To save some bandwidth, we can use AJAX to create our own brushless new log search.

In this tutorial, the table name and log view page of the database take L-Blog as an example, because my Blog program is modified from L-Blog.

The example in this tutorial has passed the actual test and can be used directly in L-Blog or FBS. Of course, you still need to do some beautification and Improvement for real application.

In the database, the log content data table is named blog_Content. The log ID is log_ID, the log title is log_Title, the log view page is blogview. asp, and the parameter is the log logID. With these materials, you can create an XML document template for search results. When displaying search results, you must display the log title and log ID to create a link to view logs.

Search Result template sample. xml

Copy codeThe Code is as follows: <? Xml version = "1.0" encoding = "UTF-8"?>
<Blogsearch>
<! -- Each reslut is a search result -->
<Result>
<! -- Log ID -->
<Logid> 1 </logid>
<! -- Log title -->
<Logtitle> AJAX first-time experience </logtitle>
</Result>
</Blogsearch>

Each result is a search result. To handle the situation where no relevant content is found, I define the logid as # When the search result is empty #.
After completing the XML document template, you can use ASP to dynamically generate the XML document required for search results. The search keyword is passed in POST mode.

Search result output ajaxsearch. asp

Copy codeThe Code is as follows: <! -- # Include file = "commond. asp" -->
<! -- # Include file = "include/function. asp" -->
<%
'Commond. asp is the database connection file
'Function. asp has the function CheckStr to be used.
Dim Search_Word, XML_Result, rsSearch, sqlSearch
Set rsSearch = Server. CreateObject ("ADODB. RecordSet ")
'Get the search keyword
Search_Word = CheckStr (Trim (Request. Form ("searchword ")))
'Xml Document Header
XML_Result = "<? Xml version = "" 1.0 "" encoding = "" UTF-8 ""?> <Blogsearch>"
IF Search_Word <> Empty Then
'Create a query SQL statement
SqlSearch = "SELECT log_ID, log_Title, log_Content FROM blog_Content WHERE log_Title LIKE '%" & Search_Word & "%' AND log_IsShow = True order by log_ID DESC"
'Open record set
RsSearch. open sqlSearch, Conn, 1, 1
'If there is no search result, a result is generated. The logid is #, which indicates no search result.
IF rsSearch. bof and rsSearch. EOF Then XML_Result = XML_Result & "<result> <logid >#</logid> <logtitle/> </result>"
'Output the search result cyclically
Do While Not rsSearch. EOF
'Output every result cyclically
XML_Result = XML_Result & "<result> <logid>" & rsSearch ("log_ID") & "</logid> <logtitle> <! [CDATA ["& rsSearch (" log_Title ") &"]> </logtitle> </result>"
RsSearch. MoveNext
Loop
Else
'If the keyword is null, no search result is returned.
XML_Result = XML_Result & "<result> <logid >#</logid> <logtitle/> </result>"
End IF
XML_Result = XML_Result & "</blogsearch>"
'Set MIME Type to XML document
Response. ContentType = "application/xml"
'Response. CharSet = "UTF-8"
'Output search results
Response. Write (XML_Result)
%>

With the output of the background search results, you can start to write the front-end search results.
First, you need to enter the search keywords and display the search results. I use div to display these two parts separately:

Ajaxsearch.htm

Copy codeThe Code is as follows: <! -- JavaScript is used and external links are imported. -->
<Script type = "text/javascript" src = "ajaxsearch. js"> </script>
<! -- User input -->
<Div>
<! -- Because no form is used, the keydown event of input must be processed. Search after the user presses enter -->
<Input type = "text" id = "searchword" onkeydown = "if (event. keyCode = 13) AjaxSearch ();"/>
<! -- Search button -->
<Input type = "button" onclick = "AjaxSearch ();" value = "Search"/>
</Div>
<! -- Search result display part -->
<Div id = "search_result">
<! -- Prompt the user to enter a search keyword at the beginning -->
<Ul> <li> enter keywords </li> </ul>
</Div>

After completing the user input and result output, you can start to write the final part-the client program.
The first step is to create an XMLHttpRequest object. This part of the code is no longer mentioned. You should be able to understand this code when you have some access to AJAX. The previous tutorial also has a detailed comment:

Ajaxsearch. js (part1)

Copy codeThe Code is as follows: var xmlObj = false;
Var xmlResult;
Try {
XmlObj = new XMLHttpRequest;
}
Catch (e ){
Try {
XmlObj = new ActiveXObject ("MSXML2.XMLHTTP ");
}
Catch (e2 ){
Try {
XmlObj = new ActiveXObject ("Microsoft. XMLHTTP ");
}
Catch (e3 ){
XmlObj = false;
}
}
}
If (! XmlObj ){
Alert ("XMLHttpRequest init Failed! ");
}

Next, send the search request:

Ajaxsearch. js (part2)

Copy codeThe Code is as follows: function AjaxSearch (){
Var searchword;
// Obtain the search keyword and perform URLEncode
Searchword = escape (document. getElementById ("searchword"). value );
If (searchword = ""){
// If the keyword is null, the user is prompted to enter the keyword
Document. getElementById ("search_result"). innerHTML = "<ul> <li> enter a keyword! </Li> </ul> ";
Return;
}
// Prompt, searching
Document. getElementById ("search_result"). innerHTML = "<ul> <li> loading. Please wait </li> </ul> ";
// Open a connection and use POST
XmlObj. open ("POST", "ajaxsearch. asp", true );
// Set the request header. The form content format is URLEncoded.
XmlObj. setRequestHeader ("Content-Type", "application/x-www-form-urlencoded ");
// Set the response function after the request is complete
XmlObj. onreadystatechange = function (){
// Complete the response
If (xmlObj. readyState = 4 ){
// The status is normal.
If (xmlObj. status = 200 ){
// Set xmlResult as the search result XML document
XmlResult = xmlObj. responseXML;
// Call AjaxShowResult () to display the search result
AjaxShowResult ();
}
}
}
// Send a request whose content is a search keyword
XmlObj. send ("searchword =" + searchword );
}

Finally, the search result is displayed:

Ajaxsearch. js (part3)

Copy codeThe Code is as follows: function AjaxShowResult (){
Var results, I, strTemp;
// Obtain the search result set
Results = xmlResult. getElementsByTagName ("result ");
// Use an unordered list to Display Search Results
StrTemp = "<ul> ";
// First, judge whether the search result is null.
If (results [0]. getElementsByTagName ("logid") [0]. firstChild. data = "#")
// If it is null, no matching search results are displayed.
StrTemp = strTemp + "<li> no search results </li> ";
Else
// Output each search result cyclically
For (I = 0; I <results. length; I ++)
StrTemp = strTemp + "<li> <a href = 'blogview. asp? LogID = "+ results [I]. getElementsByTagName ("logid") [0]. firstChild. data + "'>" + results [I]. getElementsByTagName ("logtitle") [0]. firstChild. data + "</a> </li> ";
StrTemp = strTemp + "</ul> ";
// Display Search Results
Document. getElementById ("search_result"). innerHTML = strTemp
}

So far, a complete AJAX instance has been completed.

Several experiences:

  • The page uses UTF-8 encoding, which saves a lot of trouble
  • When obtaining the search result, because getElementsByTagName is used, a set is returned. Therefore, you must add a subscript after the result, as shown in the example:
    Results [0]. getElementsByTagName ("logid") [0]. firstChild. data
  • We recommend that you use document. getElementById () to retrieve objects, instead of using methods such as document. all.

Package and download the three files in the instance:Ajaxsearch.rar

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.