Create a blog without refreshing search with Ajax

Source: Internet
Author: User
Tags empty header include log query table name
Ajax| Blog | refresh | no refresh

If you are not familiar with Ajax, you can take a look at this tutorial:"Ajax first experience above hand."

Now the blog is very popular, I believe that the Internet should be a little longer time friends will be here or there is a blog. For some friends who have some abilities, they may prefer to download a blog program to set up their own blog instead of using the services provided by some blog sites. And most of the blog program with the search function is to submit query keywords to the search page, and then generate search results in the background, and then presented to the user, the process of wasting some bandwidth, such as the sidebar of the blog. To conserve this bandwidth, we can use Ajax to build our own, no refresh log search.

In this tutorial, the table name and Log view page for the database is l-blog, because my blog program is modified from L-blog.

The examples in this tutorial have been tested in real life and can be used directly in L-blog or FBS. Of course, to really use the words still need to do some beautification and perfect.

The log content datasheet in the database is named Blog_content, where the log ID is log_id, the log title is Log_title, the Log View page is blogview.asp, and the parameter is log logid. With this information, you can start creating an XML document template for your search results. When you display search results, you need to display the title of the journal and the ID of the log to create a link to the view log.

Search Results Template Sample.xml

CODE:
<?xml version= "1.0" encoding= "Utf-8"?>
<blogsearch>
<!--every reslut is a search result-->
<result>
ID of the <!--log-->
<logid>1</logid>
< title of the!--log-->
<logtitle>ajax First Experience Hand </logtitle>
</result>
</blogsearch>

Each result is a search results, and in order to handle situations where the relevant content is not found, I define logid as # when the search results are empty.
After you complete the XML document template, you can use ASP to dynamically generate the XML documents needed for your search results. Search keywords are delivered by post.

Search Results Output ajaxsearch.asp

CODE:
<!--#include file= "commond.asp"
<!--#include file= "include/ function.asp
<%
' commond.asp a function to be used in the database connection file
' function.asp checkstr
Dim search_word,xml_ Result,rssearch,sqlsearch
Set rssearch=server.createobject ("ADODB. RecordSet ")
Get search keywords
search_word=checkstr (request.form (" Searchword "))
' XML document header
xml_result= ' <?xml version= "1.0" "encoding=" "Utf-8" "?><blogsearch>"
IF search_word<>empty Then
     ' Create 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 recordset
&N bsp;   rssearch.open sqlsearch,conn,1,1
    ' If no search results produce a result, Logid is #, marking no search results
    IF Rssearch.bof and rssearch.eof Then xml_result=xml_result& "<result><logid>#< /logid><logtitle/></result> "
   " circular output search results
    do, not rssearch.eof
         ' loops output each result
        Xml_result=xml_ result& "<result><logid>" &rssearch ("log_id") & "</logid><logtitle><! [cdata[] &rssearch ("Log_title") & "]]></logtitle></result>"  
         rssearch.movenext
    Loop
Else
    ' keyword is empty. Returns no search results
    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 writing the part of the foreground search.
The first need is to give users input search keywords and display search results where, I use DIV to display these two parts:

Ajaxsearch.htm

CODE:
<!--to use JavaScript, external link to-->
<script type= "Text/javascript" src= "Ajaxsearch.js" ></script>
<!--user Input part-->
<div>
<!--the KeyDown event to process input because it is not using form. Search for--> After the user presses the carriage return
<input type= "text" id= "Searchword"/>
<!--search button-->
<input type= "button" value= "Search"/>
</div>
<!--search results show part-->
<div id= "Search_result" >
< prompts the user to enter the search keyword--> at the beginning of the!--
<ul><li> Please enter the keyword </li></ul>
</div>

Completes the user input and the result output part, can begin to write the final part--the client program.
The first is to create the XMLHttpRequest object, this part of the code no longer said that a little contact with Ajax should understand this code, the previous tutorial also has detailed comments:

Ajaxsearch.js (part1)

CODE:
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!");
}

The next step is to send the search request section:

Ajaxsearch.js (part2)

CODE:


function Ajaxsearch () {


var Searchword;


//Get search keywords and perform urlencode


Searchword=escape (document.getElementById ("Searchword"). Value);


if (searchword== "") {


///If the keyword is empty, prompts the user to enter the keyword


document.getElementById ("Search_result"). innerhtml= "&lt;ul&gt;&lt;li&gt; Please enter the keyword!&lt;/li&gt;&lt;/ul&gt;";


return;


    }


//Give a hint, searching for


document.getElementById ("Search_result"). Innerhtml= "&lt;ul&gt;&lt;li&gt; is loading, please wait &lt;/li&gt;&lt;/ul&gt;";


//Open a connection with post


Xmlobj.open ("POST", "ajaxsearch.asp", true);


//Set request header, form content format is urlencoded


Xmlobj.setrequestheader ("Content-type", "application/x-www-form-urlencoded");


//Set response function after completion request


xmlobj.onreadystatechange=function () {


//Complete Response


if (xmlobj.readystate==4) {


//Status normal


if (xmlobj.status==200) {


//Set Xmlresult for search results XML document


Xmlresult=xmlobj.responsexml;


//Call Ajaxshowresult () displays search results


Ajaxshowresult ();


            }


        }


    }


//Send request, content for search keyword


xmlobj.send ("searchword=" +searchword);


}

The last is the display of the search results:

Ajaxsearch.js (PART3)

CODE:
Function Ajaxshowresult () {
    var results,i,strtemp;
   //Get the search results collection
    results=xmlresult.getelementsbytagname ("result");
   //Using unordered lists to display search results
    strtemp= "<ul>";
   //First determine if the search results are empty
    if (results[0].getelementsbytagname ("Logid") [0]. firstchild.data== "#")
       //Is empty, displays no match search results
         strtemp=strtemp+ "<li> no search results </li>";
    Else
       //loop output for each search result
         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
}

At this point, a complete Ajax instance is complete.

Several experiences:

    • The page uses UTF-8 encoding, which saves a lot of trouble
    • When retrieving the search results, the getElementsByTagName returns a set, so add the subscript after the result, as in the example:
      Results[0].getelementsbytagname ("Logid") [0].firstchild.data
    • It is recommended that you use document.getElementById () to get the object instead of using the Document.all method






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.