DIV CSS 佈局教程網

jQuery + Ajax 無刷新翻頁完整實作
編輯:JQuery特效代碼     

直接看程式碼最快。以下是一個以 JSON 與後端溝通的翻頁範例。

JavaScript 部分

var pageSize = "10";      // 每頁行數
var currentPage = "1";    // 當前頁
var totalPage = "0";      // 總頁數
var url = "activity_list.action";

$(document).ready(function () {
  // 分頁查詢
  function queryForPages() {
    $.ajax({
      url: url,
      type: 'post',
      dataType: 'json',
      data: "qo.currentPage=" + currentPage + "&qo.pageSize=" + pageSize,
      success: function (data) {
        clearDate();
        fillTable(data);
      }
    });
  }

  // 填充表格
  function fillTable(info) {
    if (info.length > 1) {
      totalPage = info[info.length - 1].totalPage;
      var tbody_content = "";   // 不初始化會顯示 "undefined"
      for (var i = 0; i < info.length - 1; i++) {
        tbody_content += "<tr>"
          + "<td>" + (i + 1 + (currentPage - 1) * pageSize) + "</td>"
          + "<td>" + info[i].title.substr(0, 20) + "</td>"
          + "<td>" + info[i].address.substr(0, 6) + "</td>"
          + "<td>" + info[i].quota_sign + "人</td>"
          + "<td>" + info[i].type + "</td>"
          + "</tr>";
      }
      $("#t_body").html(tbody_content);
    } else {
      $("#t_body").html("<div>" + info.msg + "</div>");
    }
  }

  function clearDate() { $("#t_body").html(""); }

  // 各翻頁按鈕
  $("#firstPage").click(function () { currentPage = "1"; queryForPages(); });
  $("#previous").click(function () { if (currentPage > 1) currentPage--; queryForPages(); });
  $("#next").click(function () { if (currentPage < totalPage) currentPage++; queryForPages(); });
  $("#last").click(function () { currentPage = totalPage; queryForPages(); });
});

HTML 部分

<table>
  <thead id="t_head">
    <tr><th>序號</th><th>標題</th><th>地點</th><th>已報名</th><th>類別</th></tr>
  </thead>
  <tbody id="t_body"><!-- ajax 填充 --></tbody>
</table>
<button id="firstPage">首頁</button>
<button id="previous">上一頁</button>
<button id="next">下一頁</button>
<button id="last">尾頁</button>

實務上的建議

既然已經明確設定 dataType: 'json',success 收到的就是物件,原範例中的 eval("("+data+")") 可以刪掉。另外把資料直接字串拼接進 HTML,一旦欄位內容含有 < > 等字元就會破壞結構,也可能帶來 XSS 風險;改用 $("<tr></tr>").text(value) 逐格填入是更安全的做法。

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