在與後端互動時,JSON 是最常見的資料交換格式。本文示範如何用 jQuery 的 ajax 與 getJSON 方法取得並處理 JSON 資料,並說明後端 ashx 的設定要點。
<script src="/js/jquery-1.4.js"></script>
<script>
// 方法一:使用 $.ajax
function jsonTest1(){
$.ajax({
url: "Handler.ashx",
data: {"type":"ajax"},
datatype: "json",
type: "get",
success: function(data){
// 因為 mime 類型是 text,返回的是 json 格式的字串
document.getElementById('div1').innerHTML = data;
}
});
}
// 方法二:使用 $.getJSON
function jsonTest2(){
$.getJSON('Handler.ashx', {'type':'json','name':'qixuejia'}, function(data){
for(var i=0; i<data.length; i++){
alert(data[i]["UserId"]);
}
});
}
</script>
<input type="button" value="jQuery.ajax()" onclick="jsonTest1()" />
<input type="button" value="jQuery.getJSON()" onclick="jsonTest2()" />
查看 jQuery 原始碼可以發現,getJSON 其實就是 ajax 的一層封裝:
getJSON: function(url, data, callback){
return jQuery.get(url, data, callback, "json");
}
它預設以 GET 方式請求,並自動把回傳結果解析為 JSON 物件,省去手動轉型的麻煩。
若要回傳 JSON 格式的物件,需把回應的 ContentType 設為 application/json;若只是回傳純文字則設為 text/plain:
public void ProcessRequest(HttpContext context){
if (context.Request.Params["type"].Equals("ajax")){
context.Response.ContentType = "text/plain";
} else {
context.Response.ContentType = "application/json";
}
GetInfo(context);
}
public void GetInfo(HttpContext context){
var listUser = UserInfoManage.GetUserInfoBySQL("Select Top 5 * From Userinfo");
IsoDateTimeConverter timeConverter = new IsoDateTimeConverter();
timeConverter.DateTimeFormat = "yyyy'-'MM'-'dd' 'HH':'mm':'ss";
string ResJsonStr = JsonConvert.SerializeObject(listUser, timeConverter);
context.Response.Write(ResJsonStr);
}
這裡用 Json.NET 的序列化方法把物件轉成 JSON 字串,並透過 IsoDateTimeConverter 統一日期格式。掌握這套前端請求與後端序列化的搭配,就能輕鬆完成 Ajax 的資料異步交換。