Home Database Mysql Tutorial 用AjaxPro实现无刷新翻页效果及数据库分页技术介绍

用AjaxPro实现无刷新翻页效果及数据库分页技术介绍

Jun 07, 2016 pm 03:30 PM
Pagination refresh accomplish technology Effect database Turn page

在看本文之前,建议查看本人的系列文章: 《AjaxPro与服务器端交互过程中如何传值》:http://blog.csdn.net/zhoufoxcn/archive/2008/01/05/2026908.aspx 《用AjaxPro实现二级联动》:http://blog.csdn.net/zhoufoxcn/archive/2008/01/07/2029204.aspx 《用Aj

在看本文之前,建议查看本人的系列文章:
《AjaxPro与服务器端交互过程中如何传值》:http://blog.csdn.net/zhoufoxcn/archive/2008/01/05/2026908.aspx
《用AjaxPro实现二级联动》:http://blog.csdn.net/zhoufoxcn/archive/2008/01/07/2029204.aspx
《用AjaxPro实现定时刷新效果》:http://blog.csdn.net/zhoufoxcn/archive/2008/03/09/2160407.aspx
以便对AjaxPro有个初步印象。

 题外话:经不住一些朋友的一再要求,一气写了这么几篇Ajax方面的文章,这其中大部分代码都是从我的项目中摘取出来的,不过为了演示整个程序的框架结构,所以在演示程序代码里不会有大量与实际相关的业务逻辑处理,但是这并不妨碍你利用这些理论做出复杂的、完善的应用。

一、数据库分页理论
在实际项目中经常会遇到一个表里有几K、几M以上的数据,而呈现给用户时并不会一下子都显示出来,所以都是分批展示给用户,这样一来可以减小网络传输量,二来也减轻服务器压力。

通常在不同数据库中都有查询从第N条到第M条记录的方法(M>N>=0),不过其效率和性能都不太一样。假如有如下一个表:

DROP TABLE IF EXISTS `zhoufoxcn`.`userlist`;
CREATE TABLE  `zhoufoxcn`.`userlist` (
  `UserId` 
int(10) unsigned NOT NULL auto_increment,
  `UserName` 
varchar(45NOT NULL,
  `Age` 
int(10) unsigned NOT NULL default '10',
  `Sex` 
tinyint(3) unsigned NOT NULL default '1',
  `Tall` 
int(10) unsigned NOT NULL,
  `Salary` 
int(10) unsigned NOT NULL,
  
PRIMARY KEY  (`UserId`)
) ENGINE
=InnoDB AUTO_INCREMENT=694 DEFAULT CHARSET=utf8;

以上是我今天演示要用到的一个MySQL中的表,对于同样结构的表,查询从第N条到第M条记录的方法在MySQL中表示为:

select * from userlist  order by userId limit n,m

MS SQL Server:

select top (m-n) * from userList where userid not in
(
select top  n userid from userList  order by userid) order by userid

Oracle:

select * from (select rownum no,* from userlist where rownumm) where no>=n; 

另外,如果数据量小的话还可以直接用DbDataAdapter 的子类的实例的public int Fill (int startRecord,int maxRecords,params DataTable[] dataTables)方法。如果数据量大的话,可能会根据实际情况采用临时表或者缓存的办法,来获得更高性能。

二、程序代码:
前台页面:

@ Page Language="C#" AutoEventWireup="true" CodeFile="AjaxPager.aspx.cs" Inherits="AjaxPager" %>

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 runat="server">
    
title>AjaxPro翻页效果title>
    
style type="text/css">
tr.items
{        
    background-color
: #8FACC2;
    border-color
:#FFFFFF;
    line-height
:18px;
}
tr.table
{        /*表格内容*/
    background-color
: #F1F3F5;
    border-color
:#FFFFFF;
    line-height
:18px;
}
    
style>
head>
body onload="JumpPage(1)">
    
form id="form1" runat="server">
    
table border="0" cellpadding="1" cellspacing="1">
    
tr>td>和谐小区青年居民概况表td>tr>
    
tr>td>
    
div id="memberList">
    数据装载中,请等待.....
     
div>
     
td>tr>
     
tr>td>说明:本名单中不包括离退休人员、残疾智障人员和儿童。td>tr>
     
table>
    
form>
    
script language="javascript" type="text/javascript" defer="defer">
        
var pageSize=20;//假定每页显示20条数据
        function JumpPage(page)//完全服务器端分页处理方法
        {
            
var label=document.getElementById("memberList");
            label.innerHTML
=AjaxPager.GetString(parseInt(page),parseInt(pageSize)).value;
        }
        
/*
        function ShowPager()
        {
        }
        
        function JumpPageClient(page)
        {
            var label=document.getElementById("memberList");
            var data=AjaxPager.GetDataTable(parseInt(page),parseInt(pageSize)).value;
            if(data!=null)
            {
            alert(data.Rows.length);
            }
            label.innerHTML=data.Rows.length;
            
        }
        
*/
    
script>
body>
html>

后台代码:

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Caching;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text;
using MySql.Data.MySqlClient;
using MySql.Data.Types;

/// 


/// 说明:本文介绍如何利用AjaxPro技术实现翻页时局部刷新,同时也介绍了翻页所涉及到的数据库知识(MySQL、MS SQL和Oracle)。
/// 本演示程序采用MySQL数据库,数据库中的数据是采用程序随机生成的。
/// 首发地址:http://blog.csdn.net/zhoufoxcn/archive/2008/03/12/2174234.aspx
/// 作者:周公
/// 日期:2008-3-12
/// 
public partial class AjaxPager : System.Web.UI.Page
{
    
protected void Page_Load(object sender, EventArgs e)
    {
        AjaxPro.Utility.RegisterTypeForAjax(
typeof(AjaxPager));
    }

    
/// 
    
/// 从数据库中指定位置读取指定数目的数据
    
/// 
    
/// 记录的起始页位置
    
/// 要读取的记录条数
    
/// 
    [AjaxPro.AjaxMethod]
    
public DataTable GetDataTable(int pageIndex, int size)
    {
        MySqlConnection connection 
= new MySqlConnection(ConfigurationManager.ConnectionStrings["MySql"].ConnectionString);
        MySqlDataAdapter adapter 
= new MySqlDataAdapter("select * from userlist limit " + (pageIndex-1* size + "," + size, connection);
        DataTable data 
= new DataTable();
        adapter.Fill(data);
        connection.Close();
        adapter.Dispose();
        
return data;
    }
    
/// 
    
/// 传递div节点的html字符串
    
/// 
    
/// 记录的起始页位置
    
/// 要读取的记录条数
    
/// 
    [AjaxPro.AjaxMethod]
    
public string GetString(int pageIndex, int size)
    {
        StringBuilder text 
= new StringBuilder();
        text.Append(
"");
        text.Append(
"");
        text.Append(
"");
        text.Append(
"");
        text.Append(
"");
        text.Append(
"");
        text.Append(
"");
        text.Append(
"");
        text.Append(
"");
        DataTable source 
= GetDataTable(pageIndex,size);
        DataRow row;
        
for (int i = 0; i  source.Rows.Count; i++)
        {
            row 
= source.Rows[i];
            text.Append(
"
");
            
for (int column = 0; column  source.Columns.Count; column++)
            {    
                text.Append(
"
");
            }
            text.Append(
"");
        }
        
int pageCount=(int)(Math.Ceiling(GetRecordCount()/(double)size));
        text.Append(
"");
        text.Append(
"");
        
if (pageIndex  pageCount)
        {
            text.Append(
"
");
        text.Append(
"
编号 姓名 年龄 性别 身高 工资
" + row[column].ToString() + "
首页 " + (pageIndex+1+ "");
        }
        
else
        {
            text.Append(
"");
        }
        
if (pageIndex > 1)
        {
            text.Append(
"
" + (pageIndex-1)+ "");
        }
        
else
        {
            text.Append(
"");
        }
        text.Append(
"
" + pageCount + ")'>尾页 ");
        text.Append(
"
当前页:"+pageIndex+"/"+pageCount+"
");
        
return text.ToString();
    }
    
/// 
    
/// 返回记录总条数
    
/// 
    
/// 
    [AjaxPro.AjaxMethod]
    
public int GetRecordCount()
    {
        MySqlConnection connection 
= new MySqlConnection(ConfigurationManager.ConnectionStrings["MySql"].ConnectionString);
        MySqlCommand command 
= new MySqlCommand("select count(userId) from userlist", connection);
        connection.Open();
        
int count = int.Parse(command.ExecuteScalar().ToString());
        connection.Close();
        command.Dispose();
        
return count;
    }
}

程序的运行效果:
用AjaxPro实现无刷新翻页效果及数据库分页技术介绍

用AjaxPro实现无刷新翻页效果及数据库分页技术介绍

用AjaxPro实现无刷新翻页效果及数据库分页技术介绍

最后说明:细心的朋友也许还会发现程序中public DataTable GetDataTable(int pageIndex, int size)也有AjaxMethod属性,我原本打算将这个方法写完的,可是现在时间太晚,留待大家实现了。这也就是另外一种办法:向客户端返回一个DataTable,在客户端将DataTable内的数据加工一下,它与我现在展示的方法区别是一个在服务器端、一个在客户端实现拼接div层的innerHtml方法。在服务器拼接的优点是纯cs代码,开发效率高,但是较真地说它占用了服务器资源;在客户端拼接的办法的优点就是拼接时不占用服务器资源,运行效率高,但是编写的时候效率较低。

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Easily understand 4K HD images! This large multi-modal model automatically analyzes the content of web posters, making it very convenient for workers. Easily understand 4K HD images! This large multi-modal model automatically analyzes the content of web posters, making it very convenient for workers. Apr 23, 2024 am 08:04 AM

A large model that can automatically analyze the content of PDFs, web pages, posters, and Excel charts is not too convenient for workers. The InternLM-XComposer2-4KHD (abbreviated as IXC2-4KHD) model proposed by Shanghai AILab, the Chinese University of Hong Kong and other research institutions makes this a reality. Compared with other multi-modal large models that have a resolution limit of no more than 1500x1500, this work increases the maximum input image of multi-modal large models to more than 4K (3840x1600) resolution, and supports any aspect ratio and 336 pixels to 4K Dynamic resolution changes. Three days after its release, the model topped the HuggingFace visual question answering model popularity list. Easy to handle

The screen is good for playing games. Brief analysis of iQOO Neo9S Pro+ screen The screen is good for playing games. Brief analysis of iQOO Neo9S Pro+ screen Jul 19, 2024 pm 03:53 PM

In today's smartphone market, screen quality has become one of the key indicators to measure the overall performance of a mobile phone. iQOO's Neo series has always been committed to providing users with excellent gaming experience and visual enjoyment. The latest product iQOO Neo9SPro+ uses a "Three Good Eye Protection Gaming Screen". Next, let's take a look at the quality of this screen. How brilliant. iQOO Neo9S Pro+ is equipped with a 1.5 KOLED e-sports direct screen, which supports flagship LTPO adaptive refresh rate from 1Hz to 144Hz, which means that it can achieve ultra-low power standby state when displaying static content, and it can also be intelligent during gaming. Switch to dynamic high from 90Hz to 144Hz

Detailed tutorial on establishing a database connection using MySQLi in PHP Detailed tutorial on establishing a database connection using MySQLi in PHP Jun 04, 2024 pm 01:42 PM

How to use MySQLi to establish a database connection in PHP: Include MySQLi extension (require_once) Create connection function (functionconnect_to_db) Call connection function ($conn=connect_to_db()) Execute query ($result=$conn->query()) Close connection ( $conn->close())

OPPO Find X7 is a masterpiece! Capture your every moment with images OPPO Find X7 is a masterpiece! Capture your every moment with images Aug 07, 2024 pm 07:19 PM

In this fast-paced era, OPPO Find X7 can use its imaging power to let us savor every beautiful moment in life. Whether it's magnificent mountains, rivers, lakes, or seas, warm family gatherings, or encounters and surprises on the street, it can help you record them with "unparalleled" picture quality. From the outside, the camera Deco design of Find It looks very recognizable and has a high-end feel. The inside is also unique, starting with the basic hardware configuration. FindX7 maintains the previous

More than just 3D Gaussian! Latest overview of state-of-the-art 3D reconstruction techniques More than just 3D Gaussian! Latest overview of state-of-the-art 3D reconstruction techniques Jun 02, 2024 pm 06:57 PM

Written above & The author’s personal understanding is that image-based 3D reconstruction is a challenging task that involves inferring the 3D shape of an object or scene from a set of input images. Learning-based methods have attracted attention for their ability to directly estimate 3D shapes. This review paper focuses on state-of-the-art 3D reconstruction techniques, including generating novel, unseen views. An overview of recent developments in Gaussian splash methods is provided, including input types, model structures, output representations, and training strategies. Unresolved challenges and future directions are also discussed. Given the rapid progress in this field and the numerous opportunities to enhance 3D reconstruction methods, a thorough examination of the algorithm seems crucial. Therefore, this study provides a comprehensive overview of recent advances in Gaussian scattering. (Swipe your thumb up

Best way to implement array pagination in PHP Best way to implement array pagination in PHP May 04, 2024 pm 02:39 PM

There are two most common ways to paginate PHP arrays: using the array_slice() function: calculate the number of elements to skip, and then extract the specified range of elements. Use built-in iterators: implement the Iterator interface, and the rewind(), key(), current(), next(), and valid() methods are used to traverse elements within the specified range.

iOS 18 adds a new 'Recovered' album function to retrieve lost or damaged photos iOS 18 adds a new 'Recovered' album function to retrieve lost or damaged photos Jul 18, 2024 am 05:48 AM

Apple's latest releases of iOS18, iPadOS18 and macOS Sequoia systems have added an important feature to the Photos application, designed to help users easily recover photos and videos lost or damaged due to various reasons. The new feature introduces an album called "Recovered" in the Tools section of the Photos app that will automatically appear when a user has pictures or videos on their device that are not part of their photo library. The emergence of the "Recovered" album provides a solution for photos and videos lost due to database corruption, the camera application not saving to the photo library correctly, or a third-party application managing the photo library. Users only need a few simple steps

Revolutionary GPT-4o: Reshaping the human-computer interaction experience Revolutionary GPT-4o: Reshaping the human-computer interaction experience Jun 07, 2024 pm 09:02 PM

The GPT-4o model released by OpenAI is undoubtedly a huge breakthrough, especially in its ability to process multiple input media (text, audio, images) and generate corresponding output. This ability makes human-computer interaction more natural and intuitive, greatly improving the practicality and usability of AI. Several key highlights of GPT-4o include: high scalability, multimedia input and output, further improvements in natural language understanding capabilities, etc. 1. Cross-media input/output: GPT-4o+ can accept any combination of text, audio, and images as input and directly generate output from these media. This breaks the limitation of traditional AI models that only process a single input type, making human-computer interaction more flexible and diverse. This innovation helps power smart assistants

See all articles