Home Web Front-end JS Tutorial jquery+json achieves paging effect_jquery

jquery+json achieves paging effect_jquery

May 16, 2016 pm 03:11 PM

Json is a lightweight data exchange format. Due to its convenience in transmitting data format, today I accidentally want to apply it to paging implementation. Paging is a long-standing topic in web development, and its application is efficient and important. Not much to say about sex
The main technologies of this article: reflection mechanism, Json data format, jquery
For the versatility of the application, the reflection mechanism must first be used to convert any type of result object to be returned into a Json type format.

public static String toJSON(Object obj) {
HashMap map = new HashMap();
Class c = obj.getClass();
// 利用反射机 制,把里面所有的属性,反射出来使用,这样放入任何一个对象, 都可以找到他们的属性,
// 把这些属性的名,和属性的值,封装成一个map里,
Field[] fields = c.getDeclaredFields();
for (int i = 0; i < fields.length; i++) {
String name = fields[i].getName();
try {
fields[i].setAccessible(true);
Object o = fields[i].get(obj);
i f (o instanceof Number) {
map.put(""" + name + """, o.toString());
} else if (o instanceof String) {
map.put(""" + name + """, """ + o.toString() + """);
}
} catch (IllegalArgumentException e) {
} catch (IllegalAccessException e) {
}
}
/ / 把map对象变成字符串
// 这些格式还需要把=变成:
String s = map.toString();
/ /System.out.println(s);
String str = s.replaceAll(""=", "":");
//System.out.println(str);
return str;
}

Copy after login

After converting the multiple objects to be returned into Json type objects, the paging information should be added at the end, and finally the multiple Json strings will be converted into an entire Json type

{"0":{"id":"0", "name":"dong0", "age":21},
"1":{"id":"1", "name":"dong1", "age":21},
"2":{"id":"2", "name":"dong2", "age":21},
"3":{"id":"3", "name":"dong3", "age":21},
"4":{"id":"4", "name":"dong4", "age":21},
"5":{"id":"5", "name":"dong5", "age":21},
"6":{"id":"6", "name":"dong6", "age":21},
"7":{"id":"7", "name":"dong7", "age":21},
"8":{"id":"8", "name":"dong8", "age":21},
"9":{"id":"9", "name":"dong9", "age":21},
"10":{"firstPage":1, "currentPage":1, 
"default_Record_Num":10, "lastPage":10, "frontPage":1, "sum":100, "nextPage":2},
"length":11}
Copy after login

When information is sent to the client, just use jquery to receive the object's data. In this way, the style of the foreground can be separated from the data transmitted in the background, which further simplifies the code

$.getJSON("result.jsp&#63;page="+p, function(json)
{
$("#show").html("<tr><th>用户ID</th><th>用户名</th><th>用户年龄</th></tr>");
for(var i=0 ; i<json.length-1; i++){
$("#show").append("<tr><td>"+json[i]["id"]+"</td><td>"+json[i]["name"]+"</ td><td>"
+json[i]["age"]+"</td></tr>");
}
$("#currentPage").attr("value",json[json.length-1]["currentPage"]);
$("#pageCount").attr("value",json[json.length-1]["lastPage"]);
});
Copy after login

Refresh-free paging code implemented using JQuery and JSon. The specific code is as follows

Four files required
An entity class file CategoryInfoModel.cs
a SqlHelper SQLHelper.cs
An AJAX server-side handler PagedService.ashx
A client calls the page WSXFY.htm
I won’t write CategoryInfoModel.cs and SQLHelper.cs, everyone knows what files they are
PagedService.ashx code is as follows

using System.Web.Script.Serialization; 
public void ProcessRequest(HttpContext context) 
{ 
context.Response.ContentType = "text/plain"; 
string strAction = context.Request["Action"]; 
//取页数 
if (strAction == "GetPageCount") 
{ 
string strSQL = "SELECT COUNT(*) FROM CategoryInfo"; 
int intRecordCount = SqlHelper.ExecuteScalar(strSQL); 
int intPageCount = intRecordCount / 10; 
if (intRecordCount % 10 != 0) 
{ 
intPageCount++; 
} 
context.Response.Write(intPageCount); 
}//取每页数据 
else if (strAction == "GetPageData") 
{ 
string strPageNum = context.Request["PageNum"]; 
int intPageNum = Convert.ToInt32(strPageNum); 
int intStartRowIndex = (intPageNum - 1) * 10 + 1; 
int intEndRowIndex = (intPageNum) * 10 + 1; 
string strSQL = "SELECT * FROM ( SELECT ID,CategoryName,Row_Number() OVER(ORDER BY ID ASC) AS rownum FROM CategoryInfo) AS t"; 
strSQL += " WHERE t.rownum >= " + intStartRowIndex + " AND t.rownum <= " + intEndRowIndex; 
DataSet ds = new DataSet(); 
SqlConnection conn = SqlHelper.GetConnection(); 
ds = SqlHelper.ExecuteDataset(conn, CommandType.Text, strSQL); 
List<CategoryInfoModel> categoryinfo_list = new List<CategoryInfoModel>();//定义实体集合 
for (int i = 0; i < ds.Tables[0].Rows.Count; i++) 
{ 
CategoryInfoModel categoryinfo = new CategoryInfoModel(); 
categoryinfo.CategoryInfoID = Convert.ToInt32(ds.Tables[0].Rows[i]["ID"]); 
categoryinfo.CategoryName = ds.Tables[0].Rows[i]["CategoryName"].ToString(); 
categoryinfo_list.Add(categoryinfo); 
} 
JavaScriptSerializer jss = new JavaScriptSerializer(); 
context.Response.Write(jss.Serialize(categoryinfo_list));//序列化实体集合为javascript对象 
} 
} 
Copy after login

WSXFY.htm code is as follows

<head> 
<title>无刷新分页</title> 
<script type="text/javascript" src="../Scripts/jquery-1.5.1.min.js"></script> 
<script type="text/javascript"> 
$(function () { 
$.post("PagedService.ashx", { "Action": "GetPageCount" }, function (response, status) { 
for (var i = 1; i <= response; i++) { 
var td = $("<td><a href=''>" + i + "</a></td>"); 
$("#trPage").append(td); 
td.click(function (e) { 
e.preventDefault(); //不要导向链接 
$.post("PagedService.ashx", { "Action": "GetPageData", "PageNum":$(this).text() }, function (response, status) { 
var categorys = $.parseJSON(response); 
$("#ulCategory").empty(); 
for (var i = 0; i < categorys.length; i++) { 
var category = categorys[i]; 
var li = $("<li>" + category.CategoryInfoID + "-" + category.CategoryName + "</li>"); 
$("#ulCategory").append(li); 
} 
}); 
}); 
} 
}); 
}); 
</script> 
</head> 
<body> 
<ul id="ulCategory"></ul> 
<table> 
<tr id="trPage"> 
</tr> 
</table> 
</body> 
</html> 

Copy after login

The above is the entire content of this article, I hope it can help you achieve the paging effect.

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

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)

What should I do if I encounter garbled code printing for front-end thermal paper receipts? What should I do if I encounter garbled code printing for front-end thermal paper receipts? Apr 04, 2025 pm 02:42 PM

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

Who gets paid more Python or JavaScript? Who gets paid more Python or JavaScript? Apr 04, 2025 am 12:09 AM

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

How to merge array elements with the same ID into one object using JavaScript? How to merge array elements with the same ID into one object using JavaScript? Apr 04, 2025 pm 05:09 PM

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

The difference in console.log output result: Why are the two calls different? The difference in console.log output result: Why are the two calls different? Apr 04, 2025 pm 05:12 PM

In-depth discussion of the root causes of the difference in console.log output. This article will analyze the differences in the output results of console.log function in a piece of code and explain the reasons behind it. �...

How to achieve parallax scrolling and element animation effects, like Shiseido's official website?
or:
How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? How to achieve parallax scrolling and element animation effects, like Shiseido's official website? or: How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? Apr 04, 2025 pm 05:36 PM

Discussion on the realization of parallax scrolling and element animation effects in this article will explore how to achieve similar to Shiseido official website (https://www.shiseido.co.jp/sb/wonderland/)...

Can PowerPoint run JavaScript? Can PowerPoint run JavaScript? Apr 01, 2025 pm 05:17 PM

JavaScript can be run in PowerPoint, and can be implemented by calling external JavaScript files or embedding HTML files through VBA. 1. To use VBA to call JavaScript files, you need to enable macros and have VBA programming knowledge. 2. Embed HTML files containing JavaScript, which are simple and easy to use but are subject to security restrictions. Advantages include extended functions and flexibility, while disadvantages involve security, compatibility and complexity. In practice, attention should be paid to security, compatibility, performance and user experience.

Is JavaScript hard to learn? Is JavaScript hard to learn? Apr 03, 2025 am 12:20 AM

Learning JavaScript is not difficult, but it is challenging. 1) Understand basic concepts such as variables, data types, functions, etc. 2) Master asynchronous programming and implement it through event loops. 3) Use DOM operations and Promise to handle asynchronous requests. 4) Avoid common mistakes and use debugging techniques. 5) Optimize performance and follow best practices.

See all articles