Asp+ajax to create a no-refresh news Comment System

Source: Internet
Author: User
Tags comments empty functions include object model rowcount
ajax|asp+| Refresh | no refresh

I do not know on the Chinaren alumni friends have not noticed, chinaren in many aspects after the revision of a large number of changes. For example, the message and reply is no longer like before, after each submission must reload the entire page, when the speed of the super slow, can only stare at the eyes waiting. So now this dazzling effect is how to do it, if you feel interested, then follow me down to see!

Friends who know Ajax may know that the realization of this dazzling effect is not a very difficult thing, of course, if you don't know what Ajax is, it doesn't matter, but in this section we're going to make a news review system to see what Ajax is, and first we'll get to know something about basics.

  What is Ajax?

Ajax author Jesse James Garrett in Ajax: A new approach to web apps, which refers to Ajax as the abbreviation for "Asynchronous JavaScript + xml", which is asynchronous JavaScript and XML processing. It contains:

Use XHTML and CSS for standards-based representations:
Using DOM (Document Object model) dynamic display and interactive operation;
Using XML and XSLT for data exchange and operation;
Using XMLHttpRequest to obtain asynchronous data;
Use JavaScript to bind the above technology application;
What is the difference between Ajax and traditional Web applications?

The biggest difference between Ajax and traditional Web apps is that Ajax can partially load one area of a page, rather than the traditional web after every page request must reload the entire page, especially in the page load is relatively large, the page load time is longer, the user most of the time in the waiting state, The present to the user is only a blank, and in the application of Ajax can be very good to avoid such things happen.

  What is the working principle of Ajax?

Ajax mainly requests the server through the XMLHttpRequest in the JavaScript object and updates the page based on the results of the processing. Such an update does not update the entire page, but rather makes local updates to a region based on the needs of the user and does not affect browsing in other areas while updating. For example: Sohu personal blog in each column after the refresh button.

  What is XMLDOM?

XMLDOM is the programming interface specification used to access and manipulate XML documents. XMLDOM is designed to be available in any language and any operating system. With the help of DOM, programmers can create XML documents, traverse their structure, and add, change, and delete their elements. The DOM sees the entire XML document as a tree, and the document-level element is the root of the tree.

Let's take a look at a few of the features related to this tutorial, it is worth noting that the following methods or properties are not the same object, please see the description:

getElementsByTagName method

Description: Returns the collection of elements for the specified name.

Syntax: objNodeList = Xmldocument.getelementsbytagname (tagname);

Example: Var node=xmldom.responsexml.getelementsbytagname ("pl");

GetAttribute () method

Description: Gets the attribute value of an element node

Syntax: Elementnode.getattribute (name)

Example: Var tot=xmldom.responsexml.getelementsbytagname ("pl") [0].getattribute ("tot");

ChildNodes Property

Description: Returns a list of nodes that contain all the available child nodes of the node.

Grammar: objnodelist=node.childnodes;

Example: objNodeList = Xmldoc.childnodes;

If a specific node is required, var u= xmldoc.childnodes (0);

Length Property ()

Description: Returns the number of nodes in a list of nodes

Syntax: nodelistobject.length

Example: Var len=node.length;

Now that the basics are finished, if you don't know much about it, it's a good idea to see some JavaScript-related tutorials. Let's take a look at the specific implementation principle of the news commentary system

Suppose there is a page index.asp, the top half shows the area for the comment list, and the following is the comment submission area. So how do we display comments and submit comments on such a page?

Tradition: The top half comments list is read and displayed directly through the database query statement, whenever the new comments are submitted, first pass to the processing page, processing the page after processing and then return to index.asp this page, of course, index.asp is reloaded to get new comments.

Ajax:: First the content of the list page is a separate XML file (pl_list.asp), and then index. In the upper part of the ASP, the comment requests the pl_list.asp page through XMLHttpRequest and passes the returned results to the area that needs to be updated. Submit comments Similarly, each submission takes a XMLHttpRequest request submission handler, and then updates the comment list display area.

This news comment system is divided into five parts, namely database, foreground page, JS code, server processing, CSS style.

  The design of the database

PL table:

Field name

Type

Length

Id

Automatic numbering

User

Text

20

DateAndTime

Date/Time

Content

Note

Newid

Digital

  Front page: (index.htm)

As shown in the image above, the foreground page consists of two parts, the top half is for the page review list, and the bottom half is for submitting comments. Since we are only simulating a news comment system and there is no real news page, we have adopted a default value 〈input name= "NewSID" value= "1" type= "hidden"/〉 when passing the news ID.

Code: index.htm

〈% @LANGUAGE = "VBSCRIPT" codepage= "936"%〉
〈! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd "〉
〈html xmlns= "http://www.w3.org/1999/xhtml"
〈head〉
〈meta http-equiv= "Content-type" content= "text/html; charset=gb2312 "/〉
〈title〉 Comment System 〈/title〉
〈script src= "Main.js" 〉〈/script〉
〈link href= "Main.css" rel= "stylesheet" type= "Text/css"/〉
〈/head〉
〈body〉
〈div id= "Pllist" is loading comments ...
〈script〉loaddom (); SetTimeout ("Loaddom ()", 10000); 〈/script〉
〈/div〉
〈div style= "Width:240px;font-size:12px;text-align:center"
〈fieldset〉〈legend〉 Review 〈/legend〉
Name=: 〈input "user" type= "text" style= "width:180px"/〉〈input name= "NewSID" value= "1" type= "hidden"/〉〈br/〉
Content: 〈textarea name= "Content" style= "width:180px;height:80px" 〉〈/textarea〉〈br/〉
〈input name= "Submit" value= "I want to comment" type= "button"/〉
〈/fieldset〉
〈/div〉
〈div style= "font-size:12px" id= "MSG"
〈/div〉
〈/body〉
〈/html〉

  JS code page (core part) Main.js

JS code is a core part of the system, the embodiment of Ajax is basically included in this short dozens of lines of code, is a link between the foreground and the background of a bridge, is the most important, in order to better let us understand the entire function, we will be introduced in subsection.

1, get the XMLHTTP object, create and return a XMLHTTP object.

var xhr;
function Getxhr ()
{
try {
Xhr=new ActiveXObject ("msxml2.xmlhttp");
catch (e) {
try {
Xhr=new ActiveXObject ("Microsoft.XMLHTTP");
catch (e) {
Xhr=false;
}
}
if (!xhr&&typeof xmlhttprequest!= ' undefined ')
{
Xhr=new XMLHttpRequest ();
}
return XHR;
}
function Openxhr (method,url,callback)
{
GETXHR ();
Xhr.open (Method,url);
Xhr.onreadystatechange=function ()
{
if (xhr.readystate!=4) return;
Callback (XHR);
}
Xhr.send (NULL);
}
function Loadxml (method,url,callback)
{
GETXHR ();
Xhr.open (Method,url);
Xhr.setrequestheader ("Content-type", "Text/xml");
Xhr.setrequestheader ("Content-type", "GBK");
Xhr.onreadystatechange=function ()
{
if (xhr.readystate!=4) return;
Callback (XHR);
}
Xhr.send (NULL);
}

Specific method of invocation:

Loadxml (Method,url,callback)

Method:http methods, for example: POST, get, put, and PropFind

URL: The URL address of the request, which can be either an absolute address or a relative address

Callback: Custom Return handler function

2. Get a list of comments

The main function of this code is to update the contents of the foreground page according to the information returned by the server, mainly including displaying the comment list, the comment list paging, the jump page three functions.

  Show Comments list: GetList function

function GetList (XMLDOM)
{
var Pllist=document.getelementbyid ("Pllist"); Gets the page Pllist object that is used to display comment content
var node=xmldom.responsexml.getelementsbytagname ("Pllist");//Get Pllist node collection
var tot=xmldom.responsexml.getelementsbytagname ("pl") [0].getattribute ("tot")//Get PL node tot attribute value, this refers to the total number of comments
var curpage=xmldom.responsexml.getelementsbytagname ("pl") [0].getattribute ("curpage");//Get PL node Curpage attribute, This refers to the number of pages currently in the comment list, applied to the page
if (tot!=0)//Determine if the current comment number is empty
{
var cont= "";
var len=node.length;//gets the total number of nodes in the Pllist node collection
for (Var i=0;i〈len;i++)
{
var u=node[i].childnodes (0). text;//gets the value of the first child node of the node, which means
var d=node[i].childnodes (1). text; Gets the value of the second child node of the node, which refers to the time
var co=node[i].childnodes (2). text; Gets the value of the third child node of the node, which refers to the content
var idnub=node[i].childnodes (3). text; Gets the value of node fourth child node, which means the news ID
cont+= ' 〈div class= "U" said: ' +u+ ' 〈/div〉〈div class= "D" Time: ' +d+ ' 〈/div〉〈div class= ' idnub ' style= ' Cursor:hand ' onmousemove = "This.style.background=\ ' #99cc66 \" "Delete 〈/div〉〈div class=" Co "content: ' +co+ ' 〈/div〉 '; Generate a string of comments that you get
}
var cont1=pagecount (tot,curpage);//Paging function call
Cont+=cont1;
pllist.innerhtml=cont;//to render content
}
Else
{
Pllist.innerhtml= "no comment!";
}
}

  Comment List page: PageCount function

function PageCount (tot,cur)
{
var cont1= "";
if (tot%5==0)//default per page five, this requirement is consistent with the server side
{
Pages=parseint (TOT/5);
}
Else
{
Pages=parseint (TOT/5) +1;
}
for (Var j=1;j〈=pages;j++)
{
if (j==cur)
{cont1+= "〈span〉" +j+ "〈/span〉"}
Else
{cont1+= "〈span style= ' cursor:hand;color: #0000ff ' onmouseout= ' this.style.background=\" \ "' Onmousemove= ' This.style.background=\ "#99cc66 \" ' Onclick= ' GoToPage ("+j+") ' "+j+" 〈/span〉 "}
}
return cont1;
}

  Jump Pages: GoToPage function

function GoToPage (page)
{
Loadxml ("Get", "pl_list.asp?page=" +page,getlist);
}
function loaddom ()//Periodic update comment list, initialize 10 seconds
{
Loadxml ("Get", "pl_list.asp", getlist);
SetTimeout ("Loaddom ()", 10000)
}

3. Delete comments

Function del (IDNUB)
{
var Msg=document.getelementbyid ("msg");
Msg.innertext= "is deleting ...";
Loadxml ("Get", "pl_del.asp?id=" +idnub,getdel);
}
function Getdel (XMLDOM)//event triggered after deletion, update page
{
var Msg=document.getelementbyid ("msg");
msg.innertext= "Delete success!";
Loadxml ("Get", "pl_list.asp", getlist);
}

4. Submission of comments

function fb ()//processing submission
{
var Msg=document.getelementbyid ("msg");
var User=document.getelementbyid ("User");
var Content=document.getelementbyid ("content")
var Newsid=document.getelementbyid ("NewSID")
if (user.value== "")
{
Alert ("What is called not empty!");
return false;
}
if (content.value== "")
{
Alert ("Content cannot be empty!");
return false;
}
Msg.innertext= "is commenting";
Loadxml ("Get", "pl_fb.asp?user=" +user.value+ "&content=" +content.value+ "&newsid=" +NEWSID.VALUE,GETFB);
}
function GETFB (XMLDOM)//comments triggered after the submission of events, update comments list
{
var Msg=document.getelementbyid ("msg");
Msg.innertext=xmldom.responsetext;
Loadxml ("Get", "pl_list.asp", getlist);
}

  Server handlers

According to the section of JS code page, we understand that the function of this system roughly includes the display of comments processing, comments Delete processing, comments submitted to deal with three functions, then we are based on these three features separately.

Comments on the Display processing page: pl_list.asp

This program generates XML files for the ASP, and the content of the comments is presented as XML in the form of pagination, and we can run it separately.

Code:

!--#include file= "conn.asp"--〉
〈%
Response.ContentType = "Text/xml"
Response.Expires = 0
Response.ExpiresAbsolute = Now ()-1
Response.AddHeader "Pragma", "No-cache"
Response.AddHeader "Cache-control", "private"
Response.CacheControl = "No-cache"
Response.Write ("〈?xml version=" "1.0" "encoding=" "gb2312" "?")
Currentpage=request ("page")
If currentpage= "" or int (currentpage) =0 then currentpage=1
Set Rs=server.createobject ("Adodb.recordset")
Sql= "SELECT * from PL ORDER BY id DESC"
Rs.cursorlocation=3
Rs.Open sql,conn,1,1
If not rs.bof or not rs.eof then
Rs.pagesize=5
Rs.absolutepage=currentpage
Rowcount=rs.pagesize
Response.Write ("〈pl tot=" "&rs.recordcount&" "curpage=" "¤tpage&")
Do, not rs.eof and rowcount〉0
Response.Write ("〈pllist〉")
Response.Write ("〈user〉" &rs ("User") & "〈/user〉")
Response.Write ("〈dateandtime〉" &rs ("DateAndTime") & "〈/dateandtime〉")
Response.Write ("〈content〉" &rs ("Content") & "〈/content〉")
Response.Write ("〈id〉" &rs ("id") & "〈/id〉")
Response.Write ("〈/pllist〉")
Rowcount=rowcount-1
Rs.movenext
Loop
Else
Response.Write ("〈pl tot=" "&rs.recordcount&" "curpage=" "¤tpage&")
End If
Rs.close
Set rs=nothing
Response.Write ("〈/pl〉")
%〉

  conn.asp database link file, used in delete and submit processing

〈%
Dim conn
Dim connstr
Dim db
db= "Main.mdb" Database file location
Connstr= "Provider=Microsoft.Jet.OLEDB.4.0;Data source=" & Server.MapPath ("&db&")
Set Conn=server.createobject ("ADODB. CONNECTION ")
Conn.Open ConnStr
%〉

  Comments on the Delete processing page: pl_list.asp

〈% response.charset= "gb2312"%〉
〈% session.codepage=936%〉
!--#include file= "conn.asp"--〉
〈%
Id=request ("id")
If id= "" Then
Response.Write ("Parameter Error!")
Response. End ()
End If
Set Rs=server. CreateObject ("Adodb.recordset")
Sql= "SELECT * from pl where id=" &id
Rs.Open sql,conn,1,3
Rs.delete
Rs.update
Rs.close
Set rs=nothing
Response.Write ("Delete succeeded!")
%〉

  Submission Processing page for comments: pl_fb.asp

〈% response.charset= "gb2312"%〉
〈% session.codepage=936%〉
!--#include file= "conn.asp"--〉
〈%
User=request ("User")
Content=request ("content")
Newsid=request ("NewSID")
Set Rs=server. CreateObject ("Adodb.recordset")
Sql= "SELECT * from PL"
Rs.Open sql,conn,1,3
Rs.addnew
RS ("user") =user
RS ("content") =content
RS ("NewSID") =newsid
RS ("DateAndTime") =time ()
Rs.update
Rs.close
Set rs=nothing
Response.Write ("Add success!")
%〉

  CSS style Main.css

A good page rendering effect can not be separated from a good style, of course, I belong to the most basic, is to see clearly, if you are interested in the style file to make changes.

. u {* * *
font-size:12px;
Float:left;
height:25px;
line-height:20px;
width:120px;
}
. d {/* time * *
font-size:12px;
Float:left;
height:25px;
line-height:20px;
width:120px;
}
. idnub {/* Delete * *
Text-align:center;
font-size:12px;
height:25px;
line-height:25px;
width:30px;
}
. Co {/* content */
font-size:12px;
width:280px;
}

This is the first time I've tried to use Ajax in ASP, accustomed to donet in the procrastination, suddenly in the most original way to write code is really a bit unaccustomed, especially the lack of the kind of WYSIWYG results, each step of the implementation must be in constant debugging to complete, is really a very tired thing. Of course, with Ajax-style program development is becoming more and more popular, now there are more and more frameworks, tools, I believe that one day, the development of AJAX applications will eventually become an easy thing.



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.