- <%@ WebHandler Language= "C#" Class= "Handler" %>
- using System;
- using System.Web;
- using System.Web.Script.Serialization;
- using System.Collections.Generic;
- public class Handler : IHttpHandler {
- public void ProcessRequest (HttpContext context) {
- context.Response.ContentType = "text/plain" ;
- Person p1 = new Person { Age = "22" , Name = "tom" };
- Person p2 = new Person { Age = "23" , Name = "jim" };
- Person p3 = new Person { Age = "24" , Name = "lilei" };
- IList<Person> persons = new List<Person> {p1,p2,p3};
- JavaScriptSerializer js = new JavaScriptSerializer();
- string s= js.Serialize(persons);
- context.Response.Write(s);
- }
- public class Person
- {
- public string Name { get; set; }
- public string Age { get; set; }
- }
- public bool IsReusable {
- get {
- return false ;
- }
- }
- }
先实例化了三个person对象,然后放到一个集合中,最后把这个集合序列化成字符串流到客户端;
客户端:
- <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
- "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd" >
- <html xmlns= "http://www.w3.org/1999/xhtml" >
- <head>
- <title></title>
- <script src= "../myjs/jquery-1.4.2.js" type= "text/javascript" ></script>
- <script type = "text/javascript" >
- $.get( "Handler.ashx" , function (data) {
- var persons = $.parseJSON(data);
- $.each(persons, function (key, person) {
- alert( "Age:" +person.Age+ "Name:" +person.Name) });
- });
- </script>
- </head>
- <body>
- </body>
- </html>