


Implement the function of automatically loading data when the page scrolls to the end based on jquery_jquery
Now, Weibo, WeChat or other applications that we often use have asynchronous loading functions. In short, when we browse Weibo or WeChat, after moving to the top or bottom of the interface, the program passes asynchronous loading This method speeds up the loading of data because it only loads a part of the data each time. When we have a large amount of data but cannot display all of it, we can consider using the asynchronous method to load the data.
Asynchronous loading of data can occur automatically when the user clicks the "View More" button or the scroll bar scrolls to the bottom of the window; in the next blog post, we will introduce how to implement the function of automatically loading more.
Figure 1 Weibo loads more functions
Text
Suppose that the user's message data is stored in our database. Now, we need to open the API interface in the form of Web Service for the client to call. Of course, we can also use a general handler (ASHX file) to let the client call ( Please refer here for details).
Datasheet
First, we create the data table T_Paginate in the database, which contains three fields ID, Name and Message, where ID is an auto-increment value.
CREATE TABLE [dbo].[T_Paginate]( [ID] [int] IDENTITY(1,1) NOT NULL, [Name] [varchar](60) COLLATE Chinese_PRC_CI_AS NULL, [Message] [text] COLLATE Chinese_PRC_CI_AS NULL, CONSTRAINT [PK_T_Paginate] PRIMARY KEY CLUSTERED ( [ID] ASC )WITH (IGNORE_DUP_KEY = OFF) ON [PRIMARY] ) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
Figure 2 Data table T_Paginate
Data Object Model
We define the data object model Message based on the data table T_Paginate, which contains three fields: Id, Name and Comment. The specific definitions are as follows:
/// <summary> /// The message data object. /// </summary> [Serializable] public class Message { public int Id { get; set; } public string Name { get; set; } public string Comment { get; set; } }
Web Service Method
Now, we need to implement the method GetListMessages(), which obtains the corresponding paging data based on the number of paging passed by the client and returns it to the client in JSON format. Before implementing the GetListMessages() method, we First, we will introduce the method of data paging query.
In the Mysql database, we can use the limit function to implement data paging query, but there is no similar function provided in SQL Server. Then, we can use our subjective initiative - implement one ourselves. The specific implementation is as follows:
Declare @Start AS INT Declare @Offset AS INT ;WITH Results_CTE AS ( SELECT ID, Name, Message, ROW_NUMBER() OVER (ORDER BY ID) AS RowNum FROM T_Paginate WITH(NOLOCK)) SELECT * FROM Results_CTE WHERE RowNum BETWEEN @Start AND @Offset
Above we defined the common table expression Results_CTE, which obtains the data in the T_Paginate table and sorts it according to the ID value from small to large, and then assigns ROW_NUMBER values according to this order, where @Start and @Offset are the data range to be queried .
Next, let us implement the method GetListMessages(), the specific implementation is as follows:
/// <summary> /// Get the user message. /// </summary> /// <param name="groupNumber">the pagination number</param> /// <returns>the pagination data</returns> [WebMethod] [ScriptMethod(ResponseFormat = ResponseFormat.Json)] public string GetListMessages(int groupNumber) { string query = string.Format("WITH Results_CTE AS (SELECT ID, Name, Message, ROW_NUMBER() OVER (ORDER BY ID) AS RowNum " + "FROM T_Paginate WITH(NOLOCK)) " + "SELECT * FROM Results_CTE WHERE RowNum BETWEEN '{0}' AND '{1}';", (groupNumber - 1) * Offset + 1, Offset * groupNumber); var messages = new List<Message>(); using (var con = new SqlConnection(ConfigurationManager.ConnectionStrings["RadditConn"].ToString())) using (var com = new SqlCommand(query, con)) { con.Open(); using (var reader = com.ExecuteReader(CommandBehavior.CloseConnection)) { while (reader.Read()) { var message = new Message { Id = (int)reader["ID"], Name = (string)reader["Name"], Comment = (string)reader["Message"] }; messages.Add(message); } } // Returns json data. return new JavaScriptSerializer().Serialize(messages); } }
Above, we defined the GetListMessages() method. For the sake of simplicity, we wrote the database operation directly on the Web Service. Please forgive me. It obtains the paging data by calling the common table expression Results_CTE. Finally, we create A JavaScriptSerializer object serializes data into JSON format and returns it to the client.
Javascript
Since we are calling the local Web Service API, we send a same-origin request to call the API interface (cross-origin request example). The specific implementation is as follows:
$.getData = function(options) { var opts = $.extend(true, {}, $.fn.loadMore.defaults, options); $.ajax({ url: opts.url, type: "POST", contentType: "application/json; charset=utf-8", dataType: "json", data: "{groupNumber:" + opts.groupNumber + "}", success: function(data, textStatus, xhr) { if (data.d) { // We need to convert JSON string to object, then // iterate thru the JSON object array. $.each($.parseJSON(data.d), function() { $("#result").append('<li id="">' + this.Id + ' - ' + '<strong>' + this.Name + '</strong>' + ' —?' + '<span class="page_message">' + this.Comment + '</span></li>'); }); $('.animation_image').hide(); options.groupNumber++; options.loading = false; } }, error: function(xmlHttpRequest, textStatus, errorThrown) { options.loading = true; console.log(errorThrown.toString()); } }); };
Above, we defined the getData() method, which uses the jQuery.ajax() method to send a same-origin request to call the GetListMessages interface. When the data is successfully loaded and displayed in the result div, the paging number (groupNumber) is increased by one.
Now, we have implemented the getData() method. Whenever the user drags the scroll bar to the bottom, the getData() method is called to obtain the data. Then, we need to combine the getData() method with the scroll bar event. Binding, the specific implementation is as follows:
// The scroll event. $(window).scroll(function() { // When scroll at bottom, invoked getData() function. if ($(window).scrollTop() + $(window).height() == $(document).height()) { if (trackLoad.groupNumber <= totalGroups && !trackLoad.loading) { trackLoad.loading = true; // Blocks other loading data again. $('.animation_image').show(); $.getData(trackLoad); } } });
Above, we implemented jQuery's scroll event. When the scroll bar scrolls to the bottom, the getData() method is called to obtain the data in the server.
CSS style
Next, we add CSS styles to the program, which are specifically defined as follows:
@import url("reset.css"); body,td,th {font-family: 'Microsoft Yahei', Georgia, Times New Roman, Times, serif;font-size: 15px;} .animation_image {background: #F9FFFF;border: 1px solid #E1FFFF;padding: 10px;width: 500px;margin-right: auto;margin-left: auto;} #result{width: 500px;margin-right: auto;margin-left: auto;} #result ol{margin: 0px;padding: 0px;} #result li{margin-top: 20px;border-top: 1px dotted #E1FFFF;padding-top: 20px;}
Picture 3 Loading more programs
Above, we implemented jQuery to automatically load more programs and send an asynchronous request to obtain data from the server whenever the scroll bar reaches the bottom.
We introduced asynchronous loading of data through jQuery through a Demo program. Of course, it also involves page query of data. Here we use a custom common table expression Results_CTE to obtain paginated data, and then, through The $.ajax() method sends a same-origin request to call the Web Service API; when the data is obtained successfully, the data is returned in JSON format. Finally, we display the data on the page.
The above is the entire content of this article, I hope it will be helpful to everyone’s study.

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Dreamweaver Mac version
Visual web development tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

WebStorm Mac version
Useful JavaScript development tools

Zend Studio 13.0.1
Powerful PHP integrated development environment
