DIV CSS 佈局教程網

再封裝 jQuery ajax:一個函式搞定 JSON 與純文字請求
編輯:JavaScript綜合知識     

專案裡到處散落 $.ajax 的參數設定,維護起來相當痛苦。把常用模式包成一個通用函式,呼叫端就能省下大量重複程式碼。

封裝後的呼叫方式

$(function () {
  // 取回 JSON 資料
  jsonAjax("AjaxQuery.aspx", "type=json", "json", callBack);

  // 取回純文字
  jsonAjax("AjaxQuery.aspx", "id=1&name=2&type=text", "text", callBackTxt);
});

通用函式本體

/**
 * ajax POST 提交
 * @param url       請求位址
 * @param param     要送出的參數
 * @param datat     回傳型別:html / json / text
 * @param callback  成功後的回呼函式
 */
function jsonAjax(url, param, datat, callback) {
  $.ajax({
    type: "post",
    url: url,
    data: param,
    dataType: datat,
    success: callback,
    error: function () {
      // 這裡可替換成專案內統一的錯誤提示元件
      alert("請求失敗,請稍後再試");
    }
  });
}

回呼函式

function callBack(data) {
  $("#ddd").html('');
  var json = eval(data);        // 轉為陣列
  $.each(json, function (index, item) {
    var name = json[index].Name;
    var age  = json[index].Age;
    var sex  = json[index].Sex;
    $("#ddd").html($("#ddd").html() + "<br>" + name + "  " + age + "  " + sex + "<br/>");
  });
}

function callBackTxt(data) {
  $("#ccc").html(data);
}

後端以 JavaScriptSerializer 輸出 JSON

如果不打算引入第三方函式庫,.NET 內建的 JavaScriptSerializer 就夠用:

using System.Web.Script.Serialization;

protected void Page_Load(object sender, EventArgs e) {
  if (!IsPostBack) {
    string gettype = Request["type"];

    if (gettype == "text") {
      string id = Request["id"];
      string name = Request["name"];
      Response.Write((id == "1" && name == "2") ? "ok符合條件" : "sorry不符合條件");
    }
    else if (gettype == "json") {
      List<Student> list = new List<Student>();
      for (int i = 0; i < 50; i++) {
        list.Add(new Student { Name = "張三" + i, Age = i, Sex = "男" });
      }
      Response.Write(new JavaScriptSerializer().Serialize(list));
    }
    Response.End();
  }
}

public struct Student {
  public string Name;
  public int Age;
  public string Sex;
}

封裝能帶來什麼

把請求方式、錯誤處理、共用的 loading 狀態都收攏到一個地方,日後要換錯誤提示元件、加上 token 或統一日誌,都只需改一處。另外提醒兩點:eval 可用 JSON.parse 取代以避免執行任意程式碼的風險;若 dataType 已指定為 json,jQuery 會自動解析,回呼函式收到的已經是物件,不需要再轉一次。

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