本文把 jQuery 前端呼叫與 ASP.NET 的 .ashx 一般處理常式、以及 JSON 序列化之間的串接方式做個完整整理,包含幾個實務上很容易忽略的細節。
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 資料就會顯得吃力。
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 字串,否則解析環節必然出錯。
把 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);
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; } }
}
}
物件字面量表達式可以直接寫在 JS 裡,Visual Studio 甚至還會提供智慧提示:
var person = { "name": "jack", "age": 24, "sex": true };
alert(person.name);
alert(person.age);
alert(person.sex);