jquery提供的簡(jiǎn)化版的ajax調(diào)用方法通常如下:
}
$("#divWait").hide();
$("#btnPost").attr("disabled", "");
});
}
該方法參數(shù)也很多,具體可看幫助文檔。本人的常規(guī)用法
});
}
context.Response.ContentType = "application/json";
如果是返回的html或者text的話(huà)可以如下寫(xiě)法
context.Response.ContentType = "text/plain";
如果ajax方法中設(shè)置的返回值是json時(shí),ashx代碼返回的格式必須是json格式的數(shù)據(jù)。
把一個(gè)對(duì)象轉(zhuǎn)換成json格式,常用方法就是采用開(kāi)源的第三方類(lèi)庫(kù)json.net,Newtonsoft.Json.dll.
JsonConvert.SerializeObject方法就可以轉(zhuǎn)換了。返回json格式后,jquery就可以采用XXX.xxx的方式獲取值了。
JsonConvert在處理datetime格式的時(shí)候,會(huì)返回類(lèi)似1198908717056的絕對(duì)值,因此,在處理datetime的時(shí)候,要做一下轉(zhuǎn)換。具體語(yǔ)句如下:
IsoDateTimeConverter timeConverter = new IsoDateTimeConverter();
//這里使用自定義日期格式,如果不使用的話(huà),默認(rèn)是ISO8601格式
timeConverter.DateTimeFormat = "yyyy'-'MM'-'dd' 'HH':'mm':'ss";
string output = JsonConvert.SerializeObject(m, Newtonsoft.Json.Formatting.Indented, timeConverter);
此處順便提一下,javascript對(duì)json格式的數(shù)據(jù)有著天生的處理能力,非常好的兼容json格式數(shù)據(jù)。
舉個(gè)例子:
ashx完整代碼如下:
namespace nnn
{
/// <summary>
/// PostIt 的摘要說(shuō)明
/// </summary>
public class PostIt : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "application/json";
try
{
string msgContent = context.Request["msgContent"] ?? "";
ModelContent m = new ModelContent()
{
author = "",
categoryid = -1,
title = "",
content = msgContent,
datetime = DateTime.Now,
key = "",
createdate = DateTime.Now,
lastmodifydate = DateTime.Now,
ip = context.Request.UserHostAddress
};
//BLLContent bll = new BLLContent();
//bll.Add(m);
IsoDateTimeConverter timeConverter = new IsoDateTimeConverter();
//這里使用自定義日期格式,如果不使用的話(huà),默認(rèn)是ISO8601格式
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;
}
}
}
}
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注