作为开发中的新蜜蜂,我有一个问题,如何根据我对最佳实践的要求获取数据
我的设计是这样的。
Java 脚本(Ajax 调用)>> ashx 处理程序(命中数据库并返回数据)>> 数据库(我的值)
我需要这样的数据才能在 HTML 中呈现
var events_array = new Array();
events_array[0] = {
startDate: new Date(2013, 01, 25),
endDate: new Date(2013, 01, 25),
title: "Event 2013, 01, 25",
description: "Description 2013, 01, 25",
priority: 1, // 1 = Low, 2 = Medium, 3 = Urgent
frecuency: 1 // 1 = Daily, 2 = Weekly, 3 = Monthly, 4 = Yearly
};
events_array[1] = {
startDate: new Date(2013, 01, 24),
endDate: new Date(2013, 01, 24),
title: "Event 2013, 01, 24",
description: "Description 2013, 01, 24",
priority: 2, // 1 = Low, 2 = Medium, 3 = Urgent
frecuency: 1 // 1 = Daily, 2 = Weekly, 3 = Monthly, 4 = Yearly
}
events_array[2] = {
startDate: new Date(2013, 01, 07),
endDate: new Date(2013, 01, 07),
title: "Event 2013, 01, 07",
description: "2013, 01, 07",
priority: 3, // 1 = Low, 2 = Medium, 3 = Urgent
frecuency: 1 // 1 = Daily, 2 = Weekly, 3 = Monthly, 4 = Yearly
}
我想知道如何从我的 ashx 处理程序发送这样的数据。
我有一个 EventEnfo 类。我可以从处理程序传递 EventInfo 列表并像上面那样在数组中格式化/转换它吗? ?有什么例子吗?
请您参考如下方法:
你可以使用 JavaScriptSerializer .因此,您可以从设计一个匹配所需 JSON 结构的模型开始:
public class EventInfo
{
public DateTime startDate { get; set; }
public DateTime endDate { get; set; }
public string title { get; set; }
...
}
然后在你的处理程序中:
public void ProcessRequest(HttpContext context)
{
IEnumerable<EventInfo> result = ... fetch from db
var serializer = new JavaScriptSerializer();
context.Response.ContentType = "application/json";
context.Response.Write(serializer.Serialize(result));
}
更新:
下面是您可以如何使用结果:
$.ajax({
url: '/myhandler.ashx',
success: function(events) {
$.each(events, function() {
alert('Title of the event: ' + this.title);
})
}
});
