Home >Web Front-end >JS Tutorial >jQuery combined with AJAX to load data from the server when the page scrolls_jquery
Introduction
The text will demonstrate how to download data from the server when scrolling the scroll bar. Using AJAX technology to load data from the server can help improve the performance of any web application because when the page is opened, only one screen of data is loaded from the server. When more data is needed, the scroll bar can be scrolled with the user. Then load it from the server side.
Background
It was Facebook that prompted me to write the code that loads data from the server when the scroll bar scrolls. While browsing Facebook, I was surprised to see that as I scrolled, new data from the server started being inserted into the existing data. Then, regarding using C# to implement the same function, I searched for relevant information on the Internet, but I did not find any articles or blogs about using C# to implement this function. Of course, there are some articles on Java and PHP implementations. After reading these articles carefully, I started writing code in c#. Since my C# version was running successfully, I thought I'd share it, hence this post.
Code
With just a few lines of code we can load on scroll. When scrolling the page, a WebMethod will be called by the client and return the content to be inserted into the client. At the same time, on the client, the scroll event will be bound to a client function (document.ready). This function loads data from the server. . Let’s talk about these two server-side and client-side methods in detail below.
Server-side method: This method is used to obtain data from a database or other data sources, and generate an HTML string according to the format of the control into which the data is to be inserted. Here I just added a message with a sequence number.
[WebMethod]
$(document).ready( function() { $contentLoadTriggered = false; $("#mainDiv").scroll( function() { if($("#mainDiv").scrollTop() >= ($("#wrapperDiv").height() - $("#mainDiv").height()) && $contentLoadTriggered == false) $contentLoadTriggered == false) { $contentLoadTriggered = true; $.ajax( { type: "POST", url: "LoadOnScroll.aspx/GetDataFromServer", data: "{}", contentType: "application/json; charset=utf-8", dataType: "json", async: true, cache: false, success: function (msg) { $("#wrapperDiv").append(msg.d); $contentLoadTriggered = false; }, error: function (x, e) { alert("The call to the server side failed. " + x.responseText); } } ); } } ); } );
这里,为检查滚动条是否已经移动到了底part,使用了下side条件判断,
if($("#mainDiv").scrollTop() >= ($("#wrapperDiv").height() - $("#mainDiv").height()) && $contentLoadTriggered == false)
这个条件将判断滚动条是否已经到达了底part,当它已经移动到了底부, 动态数据将从服务器端加载,并且插入wrapperDiv。把数据插入目标div元素的客户端脚本将异步调用返回成功时执行。
success: function (msg) { $("#wrapperDiv").append(msg.d); $contentLoadTriggered = false; }
这里,你将注意到只会送到服务器端。
我粘贴了几个样图:
출력