使用 jQuery Ajax 在页面滚动时从服务器加载数据

简介

  文本将演示怎么在滚动滚动条时从服务器端下载数据。用AJAX技术从服务器端加载数据有助于改善任何web应用的性能表现,因为在打开页面时,只有一屏的数据从服务器端加载了,需要更多的数据时,可以随着用户滚动滚动条再从服务器端加载。

 背景

  是Facebook促使我写出了在滚动条滚动时再从服务器加载数据的代码。浏览facebook时,我很惊讶的发现当我滚动页面时,新的来自服务器的数据开始插入到此现存的数据中。然后,对于用c#实现同样的功能,我在互联网上了查找了相关信息,但没有发现任何关于用c#实现这一功能的文章或者博客。当然,有一些Java和PHP实现的文章。我仔细的阅读了这些文章后,开始用c#写代码。由于我的C#版本运行的很成功,所以我想我愿意分享它,因此我发表了这边文章。

 代码

  只需要很少的几行代码我们就能在滚动时完成加载。滚动页面时,一个WebMethod将被客户端调用,返回要插入客户端的内容,同时,在客户端,将把scroll事件绑定到一个客户端函数(document.ready),这个函数实现从服务器端加载数据。下面详细说说这两个服务器端和客户端方法。

  服务器端方法:这个方法用来从数据库或者其他数据源获取数据,并根据数据要插入的控件的格式来生成HTML串。这里我只是加入了一个带有序列号的消息。

1
2
3
4
5
6
7
8
9
10
11
12
[WebMethod]
public static string  GetDataFromServer()
{
    string resp = string.Empty;
    for(int i = 0; i <= 10; i++)
    {
        resp += "<p><span>"  + counter++ +
          "</span> This content is dynamically appended " +
          "to the existing content on scrolling.</p>" ;
    }
    return resp;
}

  若你要从数据库加载数据,可以如下修改代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
[WebMethod]
public static string GetDataFromServer()
    {
        DataSet ds = new DataSet();
  
        // Set value of connection string here
        string strConnectionString = ""; // Insert your connection string value here
        SqlConnection con = new SqlConnection(strConnectionString);
  
        // Write the select command value as first parameter
        SqlCommand command = new SqlCommand("SELECT * FROM Person", con);
        SqlDataAdapter adp = new SqlDataAdapter(command);
int retVal = adp.Fill(ds);
  
        string resp = string.Empty;
for (int i = 1; i <= ds.Tables[0].Rows.Count; i++)
        {
            string strComment = string.Empty;
if (ds.Tables != null)
            {
if (ds.Tables[0] != null)
                {
if (ds.Tables[0].Rows.Count > 0)
                    {
if (ds.Tables[0].Rows.Count >= i - 1)
                        {
if (ds.Tables[0].Rows[i - 1][0] != DBNull.Value)
                            {
                                strComment = ds.Tables[0].Rows[i - 1][0].ToString();
                            }
                        }
                    }
                }
            }
            resp += "<p><span>" + counter++ + "</span> " + strComment + "</p>";
        }
return resp;
    }

  客户端方法:在客户端,我使用了document.ready方法,并且把div的scroll事件绑定到了该方法上。我使用了两个div元素,mainDiv和wrapperDiv,并且给mainDiv注册了scroll事件,把动态数据插入到wrapperDiv中。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
$(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);
}
}
);
}
}
);
}
);

  这里,为检查滚动条是否已经移动到了底部,使用了下面的条件判断,

1
2
3
if($("#mainDiv").scrollTop() >=
  ($("#wrapperDiv").height() - $("#mainDiv").height()) &&
   $contentLoadTriggered == false)

  这个条件将判断滚动条是否已经到达了底部,当它已经移动到了底部,动态数据将从服务器端加载,并且插入wrapperDiv。把数据插入目标div元素的客户端脚本将在异步调用返回成功时执行。

1
2
3
4
5
success: function (msg)
{
$("#wrapperDiv").append(msg.d);
$contentLoadTriggered = false;
}

  这里,你将注意到只有在用户移动滚动到了底部时,请求才会送到服务器端。

  我粘贴了几个样图:

 Output

  原文地址:Load-Data-From-Server-While-Scrolling-Using-JQuery

原文地址:https://www.cnblogs.com/Blog-Yang/p/3328383.html