- <%@WebHandlerLanguage= "C#" Class= "Handler" %>
- usingSystem;
- usingSystem.Web;
- usingSystem.Web.Script.Serialization;
- usingSystem.Collections.Generic;
- public class Handler:IHttpHandler{
- public void ProcessRequest(HttpContextcontext){
- context.Response.ContentType= "text/plain" ;
- Personp1= new Person{Age= "22" ,Name= "tom" };
- Personp2= new Person{Age= "23" ,Name= "jim" };
- Personp3= new Person{Age= "24" ,Name= "lilei" };
- IList<Person>persons= new List<Person>{p1,p2,p3};
- JavaScriptSerializerjs= new JavaScriptSerializer();
- strings=js.Serialize(persons);
- context.Response.Write(s);
- }
- public class Person
- {
- public stringName{get;set;}
- public stringAge{get;set;}
- }
- public boolIsReusable{
- get{
- return false ;
- }
- }
- }
先实例化了三个person对象,然后放到一个集合中,最后把这个集合序列化成字符串流到客户端;
客户端:
- <!DOCTYPEhtmlPUBLIC "-//W3C//DTDXHTML1.0Transitional//EN"
- "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd" >
- <htmlxmlns= "http://www.w3.org/1999/xhtml" >
- <head>
- <title></title>
- <scriptsrc= "../myjs/jquery-1.4.2.js" type= "text/javascript" ></script>
- <scripttype= "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>