Implementation Code for Ajax to read data by PAGE

Source: Internet
Author: User

I think it is necessary to present my ajax pages to everyone. let me first talk about the implementation core of ajax paging, and then let's look at the instance effect. the so-called ajax paging is basically the same as the traditional data paging code on the server. we mainly use ajax to send the requested page number and the number of entries to be displayed on each page to the processing webpage of the server without refreshing. click this URL to view the requested data: "ajax_page.asp? Action = read & pagecount = 3 & current_page = 1"
In this URL, pagecount indicates how many data entries are displayed on each page, and current_page indicates the page number to be requested. the server returns the data you want to request based on these two parameters. let's take a look at the instance effect:
This is the front-end ajax code: Copy codeThe Code is as follows: <Head>
<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>
</Head>
<Body>
By default, 5 data entries are displayed on each page. You can set the number of entries displayed on each page in the text box below. Enter the number of entries to be displayed on each page: <input id = "edit_count" type = "text"/> <input type = "button" type = "button" value = "OK" onclick = "Read ()"/>
<Table border = "1"> <! -- This table is used to display data content -->
<Thead> <tr> <td> NO. </td> <td> content </td> </tr> </thead>
<Tbody id = "a"> </tbody>
</Table>
<Span id = "msg" style = "color: red"> </span>
<Br/>
<Ul id = "page"> <! -- Navigation -->
</Ul>
<Script type = "text/javascript">
Var All_page; // the total number of pages.
Var All_record; // The total number of records.
Var Current_page; // current page
Var PageCount; // number of entries displayed on each page
Function ajax_xmlhttp (){
// Create xmlhttpRequest in IE for all IE5.0 and later versions
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;
}
} // Cyclically create xmlhttp. End Based on IE browser
// If not, create xmlhttpRequest Based on FireFox and other browsers
If (! _ Xmlhttp & typeof XMLHttpRequest! = "Undefined ")
{
_ Xmlhttp = new XMLHttpRequest ();
}
Return _ xmlhttp;
}
// Obtain element Functions
Function $ (elem ){
Return typeof elem = "string "? Document. getElementById (elem): elem;
}
// Read data Functions
Function Read (){
If (arguments. length! = 0) {// If a parameter is passed, it indicates that you have clicked a page number.
Var e = arguments [0] | window. event; // standardize the event object
Var obj = e.tar get | e. srcElement; // gets the event object, the page number element you clicked
Current_page = parseInt (obj. innerHTML); // obtain the number value in the element to verify the page number you want to request
$ ("Msg"). innerHTML = "current" + Current_page + "page"; // prompt message: current request page
}
PageCount = $ ("edit_count"). value; // get the value of the text box
If (PageCount. length = 0) {// if the text box is empty
PageCount = 5; // by default, 5 data entries are displayed on each page.
}
Var ajax = ajax_xmlhttp (); // assign the xmlhttprequest object to a variable.
Ajax. open ("post", "ajax_page.asp? Action = read & pagecount = "+ PageCount +" & current_page = "+ Current_page, true); // sets the request method, the requested webpage, And the url's action parameter is read, asynchronous request
Ajax. onreadystatechange = function () {// You can also specify a name for the function that has been written.
If (ajax. readyState = 4) {// data returns success
If (ajax. status = 200) {// Return OK for the http Request status code
Var xmlData = ajax. responseXML; // receives the returned data in xml format and stores 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 ++) {// dynamically create a page number list
Var li = document. createElement ("li ");
Li. innerHTML = I + 1; // because I starts with 0, the page number must be displayed on the "+ 1" tab.
Li. onclick = function (e) {Read (e)}; // bind a click event to the page number of each li
Page_list.appendChild (li); // place the generated page number element in the div.
}
Var list = xmlData. getElementsByTagName ("list"); // obtain all list tags from the returned data.
If (list. length! = 0 ){
Var t = document. getElementById ("a"); // obtain the table that displays the data.
While (t. rows. length! = 0) {// when reading data, if the table already exists, all rows will be deleted.
T. removeChild (t. rows [0]);
}
For (var I = 0; I <list. length; I ++ ){
Var tr = t. insertRow (t. rows. length); // Add several rows to the table if there are several lists.
Var td = tr. insertCell (0); // ID of the first cell to store data
Td. innerHTML = list [I]. childNodes [0]. firstChild. nodeValue;
Var td = tr. insertCell (1); // The second cell stores the data content
Td. innerHTML = list [I]. childNodes [1]. firstChild. nodeValue;
}
}
}
}
}
Ajax. send (null); // submit the request. The parameter is null.
}
Read (); // run the Read function
</Script>
</Body>
</Html>

The above is the front-end code of this ajax paging tutorial. We will not talk about the html part. We will directly start the content in the script. First, we have defined four global variables:

All_page: Total number of pages.
All_Record: Total number of data records. All_Record/PageCount = All_page indicates the total number of pages.
Current_page: the page number of the current request. It is sent to the server.
PageCount: the number of entries displayed on each page, which is sent to the server.
The three custom functions I wrote in sequence are:
Ajax_xmlhttp (); this function is used to create an available XMLHTTPRequest object. If you do not know what XMLHTTPRequest is, please understand what XMLHTTPRequest is.
$ (Elem); gets the function of an element. It references an element based on the element id on the page, which is actually a document. the abbreviation and reference of getElementById. After being written as a function, you can use $ ("element id") to obtain this element.
Read (): The function used to Read data. it's also our old friend, which was used in the previous tutorials. next, let's take a closer look at what we have done in the Read () function this time.
(1): if (arguments. length! = 0) This is to determine whether a parameter is passed when the Read () function is called. if a parameter exists, it indicates that you have clicked a page number and triggered Read (). in this case, we should obtain the page number and assign the number to the Crrent_page variable. click to learn more: arguments
(2): var e = arguments [0] | window. event; standardization event object. arguments [0] is for FF browser, and window. event is for IE browser.
(3): var obj = e.tar get | e. srcElement; after the standard event object, we need to obtain the event source. that is, the element triggers the Read () function. in this case, obj is the page number element you clicked.
(4): Current_page = parseInt (obj. innerHTML); obtain the number value in the element to verify that you want to request the page number. The value will be sent to the server in the following request.
(5): PageCount = $ ("edit_count "). get the value in the text box, if you do not enter a value in the text box. five data entries are displayed on each page by default. again, we will not repeat the previous content. that is to say, I did not explain the above Code in this tutorial. in the previous tutorial, we will find related explanations.
(6): ajax. open ("post", "ajax_page.asp? Action = read & pagecount = "+ PageCount +" & current_page = "+ Current_page, true); In the request Url, we pass the Pagecount and Current_page variables to the server, after receiving these two variables, the server determines whether to enable them. if PageCount is null, the default value is 5. if Current_page is empty, the default value is 1st pages, and the corresponding data is sent back to the client.
(7): All_Record = xmlData. getElementsByTagName ("allrecord") [0]. firstChild. nodeValue; receives an allrecord label element from the server. this element contains a numeric value, which is the total number of data items.
(8): All_page = All_Record/PageCount; divide by the total number of records All_Record by PageCount equals to the total number of pages, and then we will create the current page number list based on All_page.
(9): var page_list = $ ("page"); obtain the div element that stores the page number list. while (page_list.childNodes.length! = 0) cyclically traverse the child elements in the div. delete all its child elements. different page numbers are generated each time based on the number of entries displayed on the current page. Therefore, you must delete the page number list generated in the previous request. Of course, you can also improve this practice! If you do not know what child elements are or how to delete them, see childNodes and removeChild.
(10): for (var I = 0; I <Math. ceil (All_page); I ++); uses a for loop to dynamically generate a page number list based on the total number of pages. If All_page is 5, five pages are generated. because there will be remainder. I used Math. ceil. if you do not know the functions of Math and ceil, see Math and ceil.
(11): var li = document. createElement ("li"); create a li element and assign it to a variable named li. li. innerHTML = I + 1; write the number of page numbers in the li element. because I starts from 0, all values must be 1.
(12): li. onclick = function (e) {Read (e)}; bind a click event for each li element. This is important to understand. we bound the Read (e) function to li and passed the event object using the e parameter. when you click the page number, the Read function is triggered again to Read the data. at this time, the Read (e) function is run with parameters. we obtained the page number of your request from the parameter, assigned it to Current_page, and sent it to the server using the url.
Note that the last row in the script part: Read (); at this time, Read () does not have a parameter, and the Read () is executed only when the page is opened or refreshed (), at this time, the Current_page sent by Read () to the server is empty. pageCount is 5 by default. At this time, the server receives an empty page number and only reads 5 data records to you. at the same time, I also received the total number of data records from the server, using the total number of records divided by the number of entries displayed per page. page number is created. the Read (e) function is bound to each page number. only when you click these pages, the Read (e) with parameters will Read the data again. however, the page number has been sent to the server. do you understand?
(13): page_list.appendChild (li); write the page number for li, bind the event, and add it to the obtained div element. See: appendChild

Oh, the content above is the core part of the front end of this ajax paging tutorial. The content not described is explained in the previous ajax tutorials. next let's take a look at the server source code and analyze the source code.Copy codeThe Code is as follows: <! -- # Include file = "Conn. Asp" -->
<%
'From: http://Www.Web666.Net
'Author: Kang Dong
'The above information must be retained if reprinted
'Define a variable to save xml data.
Xml = "<? Xml version = '1. 0' encoding = 'gb2312 '?> <Body>"
Action = Request. QueryString ("action") 'accepts an action in get to determine what operations the client wants to perform.
Select case action
Case "read" 'if it is read, the data read operation is performed.
Call Read
Case else
Xml = xml & "<msg> the request parameter is incorrect. Please do not try to operate it illegally! </Msg>"
End Select
Xml = xml & "</body>"
Response. Clear
Response. ContentType = "text/xml"
Response. CharSet = "gb2312"
Response. write xml
Response. End

Sub read' Custom Data Reading Process
Call openconn' open the database link
Current_Page = Request ("Current_Page") 'current page number
PageCount = request ("PageCount") 'number of entries 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', check whether the number of entries is entered correctly.
PageCount = 5
End If
SQL = "Select count (*) From page_table" 'reads the total number of data entries in the page_table table.
Set Rs = Conn. Execute (SQL) 'execute the SQL statement
Xml = xml & "<allrecord>" & Rs (0) & "</allrecord>"
If Current_Page = 1 then', If the page is 1st
SQL = "Select Top" & PageCount & "* From page_table order by id desc"
Else
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 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 next
Wend
End Sub
%>

The above is the server webpage source code requested in the ajax paging tutorial instance. I use Asp technology on the server. Of course, you can also use jsp, php ,. net. output xml data on the server. I have explained the previous ajax tutorials. so let's start with the Read process in the source code:

1. Current_Page = Request ("Current_Page"): receives the Current_page received by the client ajax using the url parameter. The requested page number
2. PageCount = Request ("PageCount"): The PageCount passed by the receiving client ajax using the url parameter. The number of entries displayed on each page
3. Determine whether Current_Page is empty. or is it a number. if not. the Current_page is equal to 1. if PageCount is empty or not a number, PageCount is equal to 5, that is, 5 data entries are read per page.
4. SQL = "Select count (*) From page_table" the function of this SQL statement is to read the total number of data records in the table, that is, the total number of data records that we call in the front-end code. read the total number and save it in an allrecord element. and then return it to the client. the client obtains this number each time it reads data. create a page number based on this number.
5. If Current_Page = 1 Then, judge whether the value of Cruuent_Page is 1. If the value is 1, run: SQL = "Select Top" & PageCount & "* From page_table order by id desc" This SQL statement is very simple. It only reads "PageCount" data in the table. if you have not set the number of entries to read at the front end. so PageCount is equal to 5, that is, only five data records are read. the read order is desc, And the read order is reverse!
6. If Else cr1__page is not equal to 1 and Current_Page is not 1 only when you click non-1st page in the page list, run the following command: 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 id desc) order by id desc", this SQL statement is the core of paging. he roughly means reading PageCount data records in the table. the data id must be smaller than the data with the smallest id in the displayed data. for example, if you click 3rd pages, the number of entries per page is 5. the id of the data to be displayed on the third page must be smaller than the data with the smallest id on the second page, because the data is read in reverse order. do you understand? If you cannot understand the meaning of the SQL statement. please refer to the SQL-related knowledge. the following code reads data from the database. I have explained it in detail in the previous articles. the ajax page is now complete!
Tip: <! -- # Include file = "Conn. asp "--> Conn. asp is the link file of my database. nothing special. you can write one by yourself. there are also a lot of ready-made code on the Internet. the name of the database table read this time: the page_table fields are ID (automatic number) and content (data content)
Let's talk about this today. If you have any questions, please add the ajax technology exchange 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.