Home Web Front-end JS Tutorial Implement the function of automatically loading data when the page scrolls to the end based on jquery_jquery

Implement the function of automatically loading data when the page scrolls to the end based on jquery_jquery

May 16, 2016 pm 03:24 PM
jquery autoload

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]


Copy after login


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; }
}
Copy after login

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
Copy after login

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);
  }
}

Copy after login

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>' + ' —&#63;' + '<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());
    }
  });
};

Copy after login

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);
    }
  }
});
Copy after login

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;}
Copy after login

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.

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)

Detailed explanation of jQuery reference methods: Quick start guide Detailed explanation of jQuery reference methods: Quick start guide Feb 27, 2024 pm 06:45 PM

Detailed explanation of jQuery reference method: Quick start guide jQuery is a popular JavaScript library that is widely used in website development. It simplifies JavaScript programming and provides developers with rich functions and features. This article will introduce jQuery's reference method in detail and provide specific code examples to help readers get started quickly. Introducing jQuery First, we need to introduce the jQuery library into the HTML file. It can be introduced through a CDN link or downloaded

How to use PUT request method in jQuery? How to use PUT request method in jQuery? Feb 28, 2024 pm 03:12 PM

How to use PUT request method in jQuery? In jQuery, the method of sending a PUT request is similar to sending other types of requests, but you need to pay attention to some details and parameter settings. PUT requests are typically used to update resources, such as updating data in a database or updating files on the server. The following is a specific code example using the PUT request method in jQuery. First, make sure you include the jQuery library file, then you can send a PUT request via: $.ajax({u

How to remove the height attribute of an element with jQuery? How to remove the height attribute of an element with jQuery? Feb 28, 2024 am 08:39 AM

How to remove the height attribute of an element with jQuery? In front-end development, we often encounter the need to manipulate the height attributes of elements. Sometimes, we may need to dynamically change the height of an element, and sometimes we need to remove the height attribute of an element. This article will introduce how to use jQuery to remove the height attribute of an element and provide specific code examples. Before using jQuery to operate the height attribute, we first need to understand the height attribute in CSS. The height attribute is used to set the height of an element

jQuery Tips: Quickly modify the text of all a tags on the page jQuery Tips: Quickly modify the text of all a tags on the page Feb 28, 2024 pm 09:06 PM

Title: jQuery Tips: Quickly modify the text of all a tags on the page In web development, we often need to modify and operate elements on the page. When using jQuery, sometimes you need to modify the text content of all a tags in the page at once, which can save time and energy. The following will introduce how to use jQuery to quickly modify the text of all a tags on the page, and give specific code examples. First, we need to introduce the jQuery library file and ensure that the following code is introduced into the page: &lt

Use jQuery to modify the text content of all a tags Use jQuery to modify the text content of all a tags Feb 28, 2024 pm 05:42 PM

Title: Use jQuery to modify the text content of all a tags. jQuery is a popular JavaScript library that is widely used to handle DOM operations. In web development, we often encounter the need to modify the text content of the link tag (a tag) on ​​the page. This article will explain how to use jQuery to achieve this goal, and provide specific code examples. First, we need to introduce the jQuery library into the page. Add the following code in the HTML file:

Understand the role and application scenarios of eq in jQuery Understand the role and application scenarios of eq in jQuery Feb 28, 2024 pm 01:15 PM

jQuery is a popular JavaScript library that is widely used to handle DOM manipulation and event handling in web pages. In jQuery, the eq() method is used to select elements at a specified index position. The specific usage and application scenarios are as follows. In jQuery, the eq() method selects the element at a specified index position. Index positions start counting from 0, i.e. the index of the first element is 0, the index of the second element is 1, and so on. The syntax of the eq() method is as follows: $("s

How to tell if a jQuery element has a specific attribute? How to tell if a jQuery element has a specific attribute? Feb 29, 2024 am 09:03 AM

How to tell if a jQuery element has a specific attribute? When using jQuery to operate DOM elements, you often encounter situations where you need to determine whether an element has a specific attribute. In this case, we can easily implement this function with the help of the methods provided by jQuery. The following will introduce two commonly used methods to determine whether a jQuery element has specific attributes, and attach specific code examples. Method 1: Use the attr() method and typeof operator // to determine whether the element has a specific attribute

Introduction to how to add new rows to a table using jQuery Introduction to how to add new rows to a table using jQuery Feb 29, 2024 am 08:12 AM

jQuery is a popular JavaScript library widely used in web development. During web development, it is often necessary to dynamically add new rows to tables through JavaScript. This article will introduce how to use jQuery to add new rows to a table, and provide specific code examples. First, we need to introduce the jQuery library into the HTML page. The jQuery library can be introduced in the tag through the following code:

See all articles