json格式数据取得2- 通过httphandler,从server侧取得 (jquery+ajax实现)

本文介绍了如何使用C#创建HttpHandler和HandlerFactory,从服务器端获取JSON数据。通过配置web.config,将JSON请求定向到处理程序,并在客户端使用jQuery和AJAX进行处理。解析JSON时应注意对象元素与C#中定义的Student类结构匹配,大小写敏感。
摘要由CSDN通过智能技术生成

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);

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值