DIV CSS 佈局教程網

jQuery Ajax 局部無刷新更新頁面內容實作
編輯:JavaScript綜合知識     

本篇文章以一個下拉選單為例,示範如何用 jQuery 的 ajax() 在不重整整頁的前提下,只更新畫面上的某個區塊。

要更新的頁面

<!DOCTYPE html>
<html>
<head>
  <title>局部更新範例</title>
  <script src="js/jquery.js" type="text/javascript"></script>
</head>
<body>
  <select id="lucky1" onchange="return duoduo();">
    <option value="1">第一期</option>
    <option value="2">第二期</option>
  </select>

  <div id="duoduo">你好</div>

  <script type="text/javascript">
    function duoduo() {
      $.ajax({
        type: 'post',                                  // 亦可為 get
        url: 'ajax.aspx',                              // 接收資料的程式
        data: 'data=' + $("#lucky1").val(),            // 多參數以 & 串接
        dataType: 'html',                              // XML / json / jsonp / script / html / text
        success: function (msg) {
          // msg 為伺服器回傳的內容
          document.getElementById("duoduo").innerHTML = msg;
        },
        error: function () {
          alert('對不起,失敗了');
        }
      });
    }
  </script>
</body>
</html>

伺服器端(ASP.NET)

protected void Page_Load(object sender, EventArgs e)
{
    if (Request.Params["data"].ToString().Equals("1"))
    {
        Response.Write("<a href='https://www.baidu.com'>第一期</a>");
    }
    else if (Request.Params["data"].ToString().Equals("2"))
    {
        Response.Write("<a href='https://www.baidu.com'>第二期</a>");
    }
}

參數說明

  • type:請求方式,可為 POST 或 GET。
  • url:請求目標位址。
  • data:送往伺服器的資料,多個參數以 & 串接。
  • dataType:預期回應的資料型別,決定 jQuery 如何解析它。
  • success / error:請求成功與失敗時 respectively 執行的回呼。

掌握這個骨架之後,替換掉 url 與回呼內容,就能延伸成任意區塊的局部更新,例如商品清單、留言列表或儀表板數字,都不必再讓整個頁面重新載入。

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