DIV CSS 佈局教程網

jQuery Ajax 四種寫法:ajax、load、get、post
編輯:JQuery特效代碼     

jQuery 提供了好幾種發 Ajax 請求的方式,從最底層到最簡便都有。這篇用一組可運行的範例把它們並排比較,包含前端介面與後端實作。

前端:四種寫法一次看

<script>
// 寫法一:$.ajax 同步取得文字檔內容
$(document).ready(function () {
  $("#b01").click(function () {
    htmlobj = $.ajax({ url: "/Content/upFile/測試.txt", async: false });
    $("#div01").html(htmlobj.responseText);
  });
});

// 寫法二:load() 直接載入並插入,可帶選擇器只取部分內容
$(document).ready(function () {
  $("#test").load("/Content/upFile/測試2.txt #p1", function (responseTxt, statusTxt, xhr) {
    if (statusTxt == "success") alert("外部內容加載成功!" + xhr);
    if (statusTxt == "error")   alert("Error: " + xhr.status + ": " + xhr.statusText);
  });
});

// 寫法三:$.get()
$(document).ready(function () {
  $("#getbutton").click(function () {
    $.get("/DownSet/index", function (data, status) {
      alert("數據:" + data + "\n狀態:" + status);
    });
  });
});

// 寫法四:$.post()(範例中誤寫為 get,正確應為 post)
$(document).ready(function () {
  $("#postbutton").click(function () {
    $.post("/CustomerInformation/getS", { par: "ww" }, function (data, status) {
      alert("數據:" + data + "\n狀態:" + status);
      $("#postText").html(data);
    });
  });
});
</script>

<div id="div04">
  <h2 id="postText">post 方法加載文本後 會在這裡顯示</h2>
  <input type="button" value="post方法獲取" id="postbutton" />
</div>

<div id="div03">
  <h2 id="getText">get 方法加載文本後 會在這裡顯示</h2>
  <input type="button" value="get方法獲取" id="getbutton" />
</div>

<div id="div02">
  <h2>jquery load 方法加載的顯示在這裡</h2>
  <h2 id="test">加載文本後 會在這裡顯示</h2>
</div>

<div id="div01">
  <h2>加載文本後 會在這裡顯示</h2>
</div>
<p><input type="button" value="加載文本" id="b01"/></p>

後端:一個簡單的 C# 方法

public string getS(string par)
{
  string content = "";
  if (par.Equals("ww"))
  {
    content = "cheng gong le";
  }
  else
  {
    content = "shi bai le";
  }
  return content;
}

四種寫法的定位

$.ajax() 是萬用基底,所有選項(type、dataType、timeout、beforeSend、error)都在這裡設定。其餘三者都是它的包裝。
load() 最省事:把回應直接塞進選到的元素,還能在 URL 後面加空格與選擇器("url #p1")只取片段。適合載入 HTML 片段的場景。
$.get() / $.post() 適合簡短的資料交換,語法直觀。

三個必須修正的示範問題

第一,async: false 是很糟的示範。 同步 Ajax 會凍結整個瀏覽器 UI 直到回應返回,使用者會以為網頁當機。而且它正是 $.ajax 回傳值能直接取 responseText 的原因——這是同步時代的寫法。現代做法一律用非同步搭配回呼或 Promise。

第二,範例中 post 按鈕實際呼叫的是 $.get。 這大概是原始程式碼的筆誤,已在上文更正為 $.post。順帶一提,$.get 與 $.post 的差別不只在語法:GET 的參數會被拼進網址,因此有長度限制且會留在瀏覽器歷史與伺服器 log 中,敏感資料一律該用 POST。

第三,缺少錯誤處理。 四個範例全都沒有 error 或 .fail(),請求失敗時畫面會靜靜地維持原狀,使用者完全不知道發生什麼事。請至少加上 .fail(function(){ alert("載入失敗,請稍後再試"); })。

最後補充一個現代寫法。上面的回呼風格在 jQuery 3 之後已可用 Promise 串接,語意更清楚:

$.get("/DownSet/index").done(function (data) {
  $("#getText").text(data);
}).fail(function () {
  alert("載入失敗");
});

而在新專案中,若非必要,直接採用 fetch() 搭配 async/await 會比引入 jQuery 更合適。

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