2011年2月27日 于新城科技园
上午说到如何通过ajax+jquery从client端取得json数据,当然那种做法一般的项目中是不会用到的。
下午整理了一下,通过httphandler,从server侧取得数据的做法。其实也比较简单。
①、用C# 做一个Httphandler 和 HandlerFactory (其实本文中不用HandlerFactory ,直接使用Httphandler 也可以,但是习惯用Factory了)
HandlerFactory 的source:
using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
namespace MyHandlers
{
public class MyHandlerFactory : IHttpHandlerFactory
{
public IHttpHandler GetHandler(HttpContext context, string requestType, string url, string pathTranslated)
{
object h = null;
// 省略若干无用的解析URL,直接写个class,然后使用反射,新规得到这个class
string className = "MyHandlers.MyJsonHandler";
try
{
h = Activator.CreateInstance(Type.GetType(className));
}
catch (Exception e)
{
throw new HttpException("error", e);
}
return (IHttpHandler)h;
}
public void ReleaseHandler(IHttpHandler handler)
{
}
}
}
Httphandler :
using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
namespace MyHandlers
{
public class MyJsonHandler : IHttpHandler
{
public bool IsReusable
{
get { return true; }
}
public void ProcessRequest(HttpContext context)
{
Student stu1 = new Student("张三", 19, 99);
Student stu2 = new Student("李四", 21, 80);
Student stu3 = new Student("王五", 18, 70);
List<Student> list = new List<Student>();
list.Add(stu1);
list.Add(stu2);
list.Add(stu3);