Như tiêu đề, bài viết sẽ hướng dẫn các bạn thực hiện load dữ liệu từ server trong khi cuộn chuột giống facebook khi mà dữ liệu của bạn lớn, và bạn chỉ muốn show dữ liệu cho tới khi nào người dùng cuộn chuột xuống dưới để xem tiếp.
Load dữ liệu từ Server trong khi cuộn chuột giống facebook
Như tiêu đề, bài viết sẽ hướng dẫn các bạn thực hiện load dữ liệu từ server trong khi cuộn chuột giống facebook khi mà dữ liệu của bạn lớn, và bạn chỉ muốn show dữ liệu cho tới khi nào người dùng cuộn chuột xuống dưới để xem tiếp.Để làm được bài này, các bạn cần chú ý chút về ajax, và jquery, cũng như một số kiến thức về webservice nhé.
Server Method: Đầu tiên là phương thức được sử dụng để lấy dữ liệu từ server, sau đó gen nó ra dạng HTML để dùng cho ajax như dưới đây
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
| [WebMethod]public static string GetDataFromServer(){DataSet ds = new DataSet();// Set value of connection string herestring strConnectionString = ""; // Insert your connection string value hereSqlConnection con = new SqlConnection(strConnectionString);// Write the select command value as first parameterSqlCommand 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;} |
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) |


Chúc bạn có một ứng dụng thú vị với bài viết này.

















0 nhận xét