DIV CSS 佈局教程網

jQuery ajax 搭配 ashx 與 JSON 的完整用法整理
編輯:JavaScript綜合知識     

本文把 jQuery 前端呼叫與 ASP.NET 的 .ashx 一般處理常式、以及 JSON 序列化之間的串接方式做個完整整理,包含幾個實務上很容易忽略的細節。

簡化版寫法:$.post

function post() {
  $("#divWait").show();
  $("#btnPost").attr("disabled", "disabled");

  $.post("../PostIt.ashx",
    { msgContent: $("#msgContent").val() },
    function (data) {
      if (data.indexOf('OK') > -1) {
        alert(data);
      }
      $("#divWait").hide();
      $("#btnPost").attr("disabled", "");
    });
}

這種寫法拿到的其實是純文字,若要處理結構化的 JSON 資料就會顯得吃力。

改用底層 $.ajax

function doPostAjax() {
  $("#divWait").show();
  $("#btnPost").attr("disabled", "disabled");

  $.ajax({
    url: '../PostIt.ashx',
    type: 'POST',
    dataType: 'json',
    data: { msgContent: $("#msgContent").val() },
    timeout: 60000,
    error: function (XMLHttpRequest, textStatus, errorThrown) {
      alert("error! " + errorThrown);
      $("#divWait").hide();
      $("#btnPost").attr("disabled", "");
    },
    success: function (data, txtStatus) {
      showContent(data.content, data.createdate);
      $("#divWait").hide();
      $("#btnPost").attr("disabled", "");
    }
  });
}

後端必須對齊的兩件事

第一,要明確設定回應的內容類型:

context.Response.ContentType = "application/json";
// 若回傳純 html 或 text,則改為
context.Response.ContentType = "text/plain";

第二,前端 dataType 宣告為 json,後端就一定要輸出合法的 JSON 字串,否則解析環節必然出錯。

物件轉 JSON:使用 Json.NET

把 C# 物件序列化最方便的方式是引入開源的 Newtonsoft.Json.dll,呼叫 JsonConvert.SerializeObject 即可,轉完前端就能用 data.xxx 直接取值。

日期格式的坑

JsonConvert 處理 DateTime 時,預設會輸出類似 1198908717056 的時間戳數字,前端拿到後還要再轉一次很麻煩。用 IsoDateTimeConverter 指定格式可以省下這個步驟:

IsoDateTimeConverter timeConverter = new IsoDateTimeConverter();
// 不指定的話預設是 ISO8601 格式
timeConverter.DateTimeFormat = "yyyy'-'MM'-'dd' 'HH':'mm':'ss";
string output = JsonConvert.SerializeObject(m, Newtonsoft.Json.Formatting.Indented, timeConverter);

ashx 完整程式碼

using System;
using System.Web;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;

namespace nnn {
  public class PostIt : IHttpHandler {
    public void ProcessRequest(HttpContext context) {
      context.Response.ContentType = "application/json";
      try {
        string msgContent = context.Request["msgContent"] ?? "";

        ModelContent m = new ModelContent() {
          content = msgContent,
          datetime = DateTime.Now,
          createdate = DateTime.Now,
          lastmodifydate = DateTime.Now,
          ip = context.Request.UserHostAddress
        };

        IsoDateTimeConverter timeConverter = new IsoDateTimeConverter();
        timeConverter.DateTimeFormat = "yyyy'-'MM'-'dd' 'HH':'mm':'ss";
        string output = JsonConvert.SerializeObject(
          m, Newtonsoft.Json.Formatting.Indented, timeConverter);

        context.Response.Write(output);
      } catch (Exception ex) {
        context.Response.Write(ex.Message);
      }
    }

    public bool IsReusable { get { return false; } }
  }
}

JavaScript 天生就懂 JSON

物件字面量表達式可以直接寫在 JS 裡,Visual Studio 甚至還會提供智慧提示:

var person = { "name": "jack", "age": 24, "sex": true };
alert(person.name);
alert(person.age);
alert(person.sex);
XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved