jQuery結合AJAX之在頁面滾動時從伺服器載入資料_jquery

來源:互聯網
上載者:User

 簡介

文本將示範怎麼在滾動捲軸時從伺服器端下載資料。用AJAX技術從伺服器端載入資料有助於改善任何web應用的效能表現,因為在開啟頁面時,只有一屏的資料從伺服器端載入了,需要更多的資料時,可以隨著使用者滾動捲軸再從伺服器端載入。
背景

是Facebook促使我寫出了在捲軸滾動時再從伺服器載入資料的代碼。瀏覽facebook時,我很驚訝的發現當我滾動頁面時,新的來自伺服器的資料開始插入到此現存的資料中。然後,對於用c#實現同樣的功能,我在互連網上了尋找了相關資訊,但沒有發現任何關於用c#實現這一功能的文章或者部落格。當然,有一些Java和PHP實現的文章。我仔細的閱讀了這些文章後,開始用c#寫代碼。由於我的C#版本啟動並執行很成功,所以我想我願意分享它,因此我發表了這邊文章。

代碼

只需要很少的幾行代碼我們就能在滾動時完成載入。滾動頁面時,一個WebMethod將被用戶端調用,返回要插入用戶端的內容,同時,在用戶端,將把scroll事件綁定到一個用戶端函數(document.ready),這個函數實現從伺服器端載入資料。下面詳細說說這兩個伺服器端和用戶端方法。

伺服器端方法:這個方法用來從資料庫或者其他資料來源擷取資料,並根據資料要插入的控制項的格式來產生HTML串。這裡我只是加入了一個帶有序號的訊息。
 
[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;
}

若你要從資料庫載入資料,可以如下修改代碼:
 
[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中。

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

這裡,為檢查捲軸是否已經移動到了底部,使用了下面的條件判斷,
 

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

這個條件將判斷捲軸是否已經到達了底部,當它已經移動到了底部,動態資料將從伺服器端載入,並且插入wrapperDiv。把資料插入目標div元素的用戶端指令碼將在非同步呼叫返回成功時執行。
 

success: function (msg){$("#wrapperDiv").append(msg.d);$contentLoadTriggered = false;}

這裡,你將注意到只有在使用者移動滾動到了底部時,請求才會送到伺服器端。

我粘貼了幾個樣圖:
Output

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.