Ajax read Data pagination display article implementation code _AJAX related

Source: Internet
Author: User
Tags numeric numeric value
I think it's still necessary to present my Ajax pagination to everyone. Let me start by talking about the implementation core of this Ajax paging, and then we'll look at the example effect. The so-called Ajax paging and the traditional data paging, the server side of the code is basically the same. The main thing we do is to use Ajax to send the requested page number, and the number of bars to be displayed per page to the server's processing page without refreshing. Click on this URL to see the requested data: "Ajax_page.asp?action=read&pagecount=3 & Current_page=1"
In this URL, PageCount represents a few pieces of data per page, Current_page represents the page number to be requested. The service side returns the data you want to request based on these two parameters. Below we look at the example effect:
This is the AJAX code for the front end:
Copy Code code as follows:

<title>ajax Data Paging </title>
<style>
body{
font-size:12px;
}
table{
Border-collapse:collapse;
}
li{
List-style:none;
BORDER:1PX solid;
width:20px;
height:20px;
Text-align:center;
margin:5px;
padding:2px;
Float:left;
Cursor:pointer;
}
</style>
<body>
The default display is 5 data per page and you can set the number of display bars per page in the text box below Enter the number of bars to display per page: <input id= "Edit_count" type= "text"/> <input "button" type= "button" type= "OK" value= "Read ( ) "/>
<table border= "1" ><!--This table is used to display data content-->
<thead><tr><td> Number </td><td> content </td></tr></thead>
<tbody id= "a" ></tbody>
</table>
<span id= "msg" style= "color:red" ></span>
<br/>
<ul id= "page" ><!--page navigation-->
</ul>
<script type= "Text/javascript" >
Total number of Var all_page;//pages
var all_record;//total number of bars
var current_page;//current Page
var pagecount;//the number of bars displayed per page
function Ajax_xmlhttp () {
Create XMLHttpRequest in IE, suitable for all versions above IE5.0
var msxmlhttp = new Array ("msxml2.xmlhttp.5.0", "msxml2.xmlhttp.4.0", "msxml2.xmlhttp.3.0", "Msxml2.xmlhttp", " Microsoft.XMLHTTP ");
for (var i=0; i<msxmlhttp.length; i++) {
Try
{
_xmlhttp=new ActiveXObject (Msxmlhttp[i]);
}
catch (E)
{
_xmlhttp=null;
}
//loop to create XMLHTTP based on IE browser. end
If not IE browser, create a browser based on Firefox XMLHttpRequest
if (!_xmlhttp && typeof XMLHttpRequest!= "undefined")
{
_xmlhttp=new XMLHttpRequest ();
}
return _xmlhttp;
}
Get Element function
function $ (elem) {
return typeof Elem = = "string"? document.getElementById (elem): Elem;
}
Reading data functions
function Read () {
if (arguments.length!=0) {//If a parameter is passed over, it proves that you clicked on a page number
var e = Arguments[0] | | window.event; Standardizing event objects
var obj = E.target | | E.srcelement; Get the Event object, the page number element you clicked
Current_page = parseint (obj.innerhtml)//Get the numeric value in the element to prove that you are asking for the first few pages
$ ("msg"). InnerHTML = "Current +current_page+" page;//Hint: page of the current request
}
PageCount = $ ("Edit_count"). value;//gets the value of the text box
if (Pagecount.length = = 0) {//If the text box is empty
PageCount = 5; Default display of 5 data per page
}
var ajax = Ajax_xmlhttp (); Assigns a XMLHttpRequest object to a variable.
Ajax.open ("Post", "Ajax_page.asp?action=read&pagecount=" +pagecount+ "& Current_page=" +current_page,true) //Set the request method, the requested Web page, the URL's action parameter is read, the asynchronous request
Ajax.onreadystatechange = function () {//You can also specify an already-written name
if (ajax.readystate = = 4) {//data returned successfully
if (Ajax.status =) {//http Request status code return OK
var xmlData = ajax.responsexml;//Receives the returned data in XML format and saves it in the XmlData variable
All_record = Xmldata.getelementsbytagname ("Allrecord") [0].firstchild.nodevalue;
All_page = All_record/pagecount;
var page_list = $ ("page");
while (page_list.childnodes.length!=0) {
Page_list.removechild (Page_list.childnodes[0]);
}
For (Var i=0;i<math.ceil (all_page); i++) {//Dynamic Create page number list
var li = document.createelement ("Li");
li.innerhtml = i+1;//because I started with 0, so I want +1 to show the page number
Li.onclick = function (e) {Read (E)};//the page number of each Li to order a hit event
Page_list.appendchild (li);//To place the generated page number elements in a div
}
var list = xmldata.getelementsbytagname ("list")//in the returned data, get all list labels
if (list.length!=0) {
var t = document.getElementById ("a");//Get the table showing the data
while (t.rows.length!=0) {//When reading data, if the table already exists rows. Delete all
T.removechild (T.rows[0]);
}
for (Var i=0;i<list.length;i++) {
var tr = T.insertrow (t.rows.length);//A few lists add a few lines to the table.
var td = Tr.insertcell (0);//The first cell holds the data number
td.innerhtml = List[i].childnodes[0].firstchild.nodevalue;
var td = Tr.insertcell (1);//The second cell holds the contents of the data
td.innerhtml = List[i].childnodes[1].firstchild.nodevalue;
}
}
}
}
}
Ajax.send (null);//commit request, parameter is NULL
}
Read ();//Run the Read function
</script>
</body>

This is the front-end code for this AJAX paging tutorial, and we're not going to talk about the HTML part. Start the contents of the script directly. First we define 4 global variables, respectively:

All_page: Total pages, basis for creating page numbers
All_record: Total number of data bars, all_record/pagecount=all_page total pages
Current_page: The page number of the current request. Delivered to the service side
PageCount: The number of bars displayed per page, delivered to the server
And then, in turn, I wrote 3 custom functions, respectively:
Ajax_xmlhttp (); The function is to create an available XMLHttpRequest object if you do not yet know what XMLHttpRequest is. Please understand what is XMLHttpRequest
$ (elem); Gets the function of an element, the reference to an element based on the ID of the element in the page, which is actually the abbreviation and reference of the document.getElementById, which can be obtained directly using $ ("Element ID") as a function.
Read (): a function that reads data. is also our old friend, in the previous several tutorials are used. Let's take a closer look at what we've done in the read () function this time.
(1): if (arguments.length!=0) This is to determine whether there are arguments passed when the read () function is called. If there is a parameter, it is shown that you clicked on a page number and triggered read (). Then we should get the page number and assign the page number to the Crrent_page variable. Click to learn: Arguments
(2): var e = arguments[0] | | Window.event standard Event object, Arguments[0] is for FF browser, window.event is IE browser
(3): var obj = E.target | | E.srcelement the event object, we want to get the source of the event. Which means that the element triggers the read () function. The obj at this point is the page number you clicked on.
(4): Current_page = parseint (obj.innerhtml); Gets the numeric value in the element to prove that you want to request the first page, which is sent to the server in the following request.
(5): PageCount = $ ("Edit_count"). Value gets the values in the text box if you don't enter a value into the text box. Then the default display of 5 data per page. Once again, we will not repeat what we have said before. That means the code I didn't explain in the tutorial. You'll find explanations in previous tutorials.
(6): Ajax.open ("Post", "Ajax_page.asp?action=read&pagecount=" +pagecount+ "& Current_page=" +current_page, True), we pass the PageCount and Current_page variables to the server in the URL of the request, and the server receives these two variables to be judged later. If PageCount is empty then the default is 5. If Current_page is blank, the default is page 1th, and then the corresponding data is passed back to the client.
(7): All_record = Xmldata.getelementsbytagname ("Allrecord") [0].firstchild.nodevalue; receives a Allrecord tag element from the server. The element contains a numeric value that is the total number of bars for the data.
(8): All_page = All_record/pagecount; The total number of All_record divided by PageCount is equal to the total page, after a few pages of data. We will create the current page number list based on All_page.
(9): var page_list = $ ("page"); Gets the div element that holds the list of page numbers. while (page_list.childnodes.length!=0) loops through the child elements within the Div. Deletes all its child elements. Each time you generate a different number of pages depending on how many bars are displayed on the current page, you must remove the list of page numbers that were generated from the last request, but you can also improve my practice! If you don't yet know what a child element is or how to delete a child element, see: ChildNodes and RemoveChild
(in): for (Var i=0;i < Math.ceil (all_page); i++); Use a For loop to generate a list of page numbers dynamically based on the total number of pages, or 5 page numbers if the All_page is 5. Because there are more than enough to consider. I used the Math.ceil. If you don't yet know the role of math and Ceil, see: Math and Ceil
(one): var li = document.createelement ("Li"); creates an LI element and assigns it to a variable named Li. li.innerhtml= i+1, write page number value within LI element. Since I was starting from 0, all to add 1.
(s): Li.onclick = function (e) {Read (e)}; Bind an event for each Li element, this is the key must be understood clearly. We have bound the Read (e) function to Li and passed the event object with the E parameter. When you click on each page number, the Read function is triggered again to read the data. The read (e) function, which runs at this time, is parameterized. We get the page number you requested from the parameter, then assign it to Current_page, and send it to the server using the URL.
You notice the last line in the script part: Read (), when read () has no parameters, and the read () is not executed until the page is opened or the page is refreshed, and the current_page sent to the server by read () is empty. PageCount default is 5, this time the server received an empty page number, will only read 5 data to you. At the same time, I also received the total number of data from the server, using the total number of bars divided by the number of bars displayed per page. The page number was created. and a Read (e) function is bound for each page number. Read (e) with parameters only when you click on these page numbers to perform data reading again. However, the read at this time has sent a page number to the server. Do you get it?
(a): Page_list.appendchild (li); the page number is written for Li, and the event is appended to the DIV element captured above. Please refer to: appendchild

Oh, the part of the story above is the core of the front end of this Ajax paging tutorial, not covered in the previous Ajax tutorials. Below we look at the source of the server and analyze the source code
Copy Code code as follows:

<!--#include file= "conn.asp"-->
<%
' From: Http://Www.Web666.Net
' Author: Kang Dong
' If you want to reprint, please be sure to keep the above information
' Define a variable to hold the XML data
Xml= "<?xml version= ' 1.0 ' encoding= ' gb2312 '?><body> '"
Action=request.querystring ("action") ' uses Get method to accept an action to determine what the client wants to do
Select Case Action
Case "read" ' If Read is performed
Call Read
Case Else
XML = xml& "<msg> Request parameter error, please do not attempt illegal operation!" </msg> "
End Select
xml=xml& "</body>"
Response.Clear
Response.contenttype= "Text/xml"
response.charset= "gb2312"
Response.Write XML
Response.End

Sub read ' Custom read data process
Call openconn ' Open database link
Current_page = Request ("current_page") ' current page number
PageCount = Request ("PageCount") ' The number of bars displayed on the current page
XML = xml& "<page>" &pagecount& "</page>"
If current_page = "" Or not IsNumeric (current_page) Then
Current_page = 1
End If
If PageCount = "" Or not IsNumeric (PageCount) Then ' Determines whether the number of bars is entered correctly
PageCount = 5
End If
SQL = "SELECT count (*) from page_table" reads the total number of data in the Page_table table
Set Rs = conn.execute (SQL) ' executes SQL statement
XML = xml& "<allrecord>" &rs (0) & "</allrecord>"
If current_page = 1 Then ' If this is the 1th page
SQL = ' Select top ' &PageCount& ' * from page_table ORDER BY id DESC '
Else
SQL = "SELECT Top" &PageCount& "* from page_table where id< (select Min (ID) to (select Top" & (Current_pag e-1) *pagecount) & "ID from page_table ORDER BY id DESC)"-ORDER BY id DESC "
End If
Set Rs=conn.execute (SQL)
While not rs.eof
XML = xml& "<list>"
XML = xml& "<id>" &rs ("id") & "</id>"
XML = xml& "<content>" &rs ("Content") & "</content>"
XML = xml& "</list>"
Rs.movenext ' The next one
Wend
End Sub
%>

The above is the server-side Web page source requested in this Ajax paging tutorial instance. I use ASP technology on the server side, of course you can also use jsp,php,.net and so on easy simulation. About outputting XML data on the server side. I've been explaining it in the previous Ajax tutorials. So we start with the read reading process in the source code:

1, current_page = Request ("Current_page"): Receive client ajax using URL parameters passed over the Current_page, the requested page number
2, PageCount = Request ("PageCount"): Receive client ajax using URL parameters passed over the PageCount, the number of bars per page
3, and then separately determine whether the current_page is empty. Or whether it is a number. If the condition is not met. Then the current_page equals 1. If the PageCount is also empty, or not a number, the PageCount equals 5, which means that 5 data per page is read
4. sql = "SELECT COUNT (*) from page_table" The function of this SQL is to read a total number of data in the table, which is what we call the total number of lines in the front-end code. The total number of items is read and stored in a ALLRECORD element. It is then passed back to the client. Each time the client reads the data, it gets the number. Based on this number, the page number is created.
5, if Current_page = 1 Then To determine whether Cruuent_page is 1, if 1 is executed: SQL = "SELECT Top" &PageCount& "* from page_table ORDER by I D desc "The meaning of this SQL statement is simple, read only the" PageCount "bar data in the table. If you do not set the number of bars to read at the front end. Then PageCount equals 5, which means reading only 5 data. Read order for DESC, reverse read!
6. Else if crrent_page is not equal to 1, only if you click on page 1th of the page number list, Current_page will not be 1, then execute: SQL = "SELECT Top" &PageCount& "* from page _table where id< (select Min (ID) from (select Top & (current_page-1) *pagecount) & ID from page_table ORDER by I D desc)), ORDER BY id DESC ", the SQL statement is the core of the paging. His general meaning is: Read the PageCount bar data in the table. The ID of the data must be less than the data with the smallest ID in the data that has been displayed. For example, you click on page 3rd, and the number of bars per page is 5. The ID of the data to be displayed on the third page must be less than the smallest number of the second page ID because it is read in reverse order. Do you get it? If you can't understand the meaning of the SQL at all. Please fill the relevant knowledge of SQL. The following code reads data from a database, and I have explained it in detail in the previous few. Ajax paging is complete!
Tip: The!--#include file= "conn.asp"-->conn.asp is my database link file. Nothing special. You should be able to write one yourself out. There are also a lot of ready-made code on the Web. This read database table name is: page_table field is ID (AutoNumber), content (data contents)
This is the place to talk today, what you don't understand. Please add AJAX Technology Group: 110167482
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.