DIV CSS 佈局教程網

jQuery 搭配 AJAX:滾動到頁面底部再向伺服器載入資料
編輯:JavaScript綜合知識     

用 AJAX 分批載入資料,對任何 Web 應用的效能都有幫助:開啟頁面時只抓一屏的量,使用者往下滑時再補抓下一批。Facebook 的動態流就是這個模式的經典案例。本文以 C# 的 WebMethod 為後端示範,前端則只需幾行程式碼。

伺服器端:WebMethod

方法負責從資料來源取得資料,並組出要插入前端的 HTML 字串。這裡先只回傳帶序號的示範內容:

[WebMethod]
public static string GetDataFromServer()
{
    string resp = string.Empty;
    for (int i = 0; i <= 10; i++)
    {
        resp += "<p>" + counter++ + " This content is dynamically appended "
              + "to the existing content on scrolling.</p>";
    }
    return resp;
}

若改成從資料庫讀,只要換掉內容來源即可:

[WebMethod]
public static string GetDataFromServer()
{
    DataSet ds = new DataSet();
    string strConnectionString = "";   // 在此填入連線字串
    SqlConnection con = new SqlConnection(strConnectionString);
    SqlCommand command = new SqlCommand("SELECT * FROM Person", con);
    SqlDataAdapter adp = new SqlDataAdapter(command);
    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[0].Rows[i - 1][0] != DBNull.Value)
        {
            strComment = ds.Tables[0].Rows[i - 1][0].ToString();
        }
        resp += "<p>" + counter++ + " " + strComment + "</p>";
    }
    return resp;
}

原範例把每一層 null 檢查都展開寫,其實可以簡化;但重點在觀念:回傳的是已組好的 HTML 片段,前端直接 append。

客戶端:綁定 scroll 事件

用兩個巢狀的 div:mainDiv 是固定高度的捲動容器,wrapperDiv 是被捲動的內容層。

$(document).ready(function () {
  var $contentLoadTriggered = false;

  $("#mainDiv").scroll(function () {
    if ($("#mainDiv").scrollTop() >= ($("#wrapperDiv").height() - $("#mainDiv").height())
        && $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("呼叫伺服器失敗。" + x.responseText);
        }
      });
    }
  });
});

判斷是否已到底部的條件是:

$("#mainDiv").scrollTop() >= ($("#wrapperDiv").height() - $("#mainDiv").height())

也就是「已捲動距離」等於或超過「內容總高減去視窗高」。而 $contentLoadTriggered 這個旗標很關鍵:AJAX 是非同步的,若沒有它,使用者在回應到達前的每一次 scroll 事件都會再發一次請求。請求成功後把旗標復位,並把新內容接到 wrapperDiv 後面。

實作上該補的防護

要有明確的終止條件。上面的程式碼如果伺服器一直回傳內容,捲動就會無止境。實務上應帶上頁碼或 cursor,並在回傳空陣列時停止綁定。

節流(throttle)。scroll 事件的觸發頻率極高,建議加上約 200 毫秒的節流,避免每次都跑一遍 DOM 計算。

把高度計算快取起來。每次 scroll 都讀 height() 會觸發版面計算,可以在載入新資料後才更新快取值。

失敗時要解除旗標。原範例在 error 分支裡沒有把 $contentLoadTriggered 復位,一旦請求失敗,後續捲動就永遠不會再觸發載入——這是很容易漏掉的細節。

拼字串組 HTML 有 XSS 風險。若資料來自使用者輸入,請改用前端轉义或 text(),後端也應輸出轉义後的內容。

這個模式今日多以 IntersectionObserver 實作偵測底部,比監聽 scroll 事件更省資源也更準確,但「分批取資料、以旗標防重複觸發、有明確結尾」這三個原則完全相同。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved