C#中将.Net对象序列化为Json字符串的方法:
JavaScriptSerializer().Serialize(p),
JavaScriptSerializer在System.Web.Extensions.dll中,
是.Net3.x 中新增的类。
完整:System.Web.Script.Serialization.JavaScriptSerializer
FormTest.html
1 <!DOCTYPE html> 2 <html xmlns="http://www.w3.org/1999/xhtml"> 3 <head> 4 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 5 <title></title> 6 <script src="js/jquery-1.7.1.min.js"></script> 7 <script> 8 $(function () { 9 $(‘#btnAdd‘).click(function () { 10 //$.post(‘FormTest.ashx‘, 11 // //‘title=‘ + $(‘#title‘).val()+‘&content=‘+$(‘#content‘).val(), 12 // //$(‘#form1‘).serialize(),//返回由name与value构成的键值对字符串 13 // $(‘#form1‘).serializeArray(),//由name与value构成的json对象的数组 14 // function(msg) { 15 // $(‘#showDiv‘).html(msg); 16 // } 17 //); 18 19 //$.getJSON( 20 // ‘FormTest.ashx‘, 21 // $(‘#form1‘).serialize(), 22 // function (data) {//{Title:***,Content:***} 23 // //{"Title":"xlb","Content":"yg"} 24 // $(‘#showDiv‘).html(‘title:‘+data.Title+‘<br>content:‘+data.Content); 25 // } 26 //); 27 28 $.getJSON( 29 ‘FormTest.ashx‘, 30 $(‘#form1‘).serializeArray(), 31 function (data) {//[{},{},{}....{}] 32 var list = $(‘#showDiv table‘); 33 $.each(data, function (index, item) { 34 list.append(‘<tr>‘ + 35 ‘<td>‘ + item.Title + ‘</td>‘ + 36 ‘<td>‘ + item.Content + ‘</td>‘ + 37 ‘</tr>‘); 38 }); 39 } 40 ); 41 }); 42 }); 43 </script> 44 45 </head> 46 <body> 47 <form id="form1"> 48 <input type="text" id="title" name="title" /> 49 <br /> 50 <input type="text" id="content" name="content" /> 51 <br /> 52 <input type="button" id="btnAdd" value="添加" /> 53 </form> 54 <div id="showDiv"> 55 <table border="1"></table> 56 </div> 57 </body> 58 </html>
FormTest.ashx
1 public class FormTest : IHttpHandler 2 { 3 4 public void ProcessRequest(HttpContext context) 5 { 6 context.Response.ContentType = "text/plain"; 7 8 string title = context.Request["title"]; 9 string content = context.Request["content"]; 10 11 //context.Response.Write(title+"-"+content); 12 13 #region 返回单一对象 14 //Result result=new Result(); 15 //result.Title = title; 16 //result.Content = content; 17 18 //JavaScriptSerializer js=new JavaScriptSerializer(); 19 //string result1 = js.Serialize(result); 20 //context.Response.Write(result1); 21 #endregion 22 23 #region 返回数组 24 List<Result> list = new List<Result>(); 25 for (int i = 0; i < 10; i++) 26 { 27 list.Add(new Result() 28 { 29 Title = title + i, 30 Content = content + i 31 }); 32 } 33 34 JavaScriptSerializer js = new JavaScriptSerializer(); 35 string result = js.Serialize(list); 36 context.Response.Write(result); 37 #endregion 38 } 39 40 public bool IsReusable 41 { 42 get 43 { 44 return false; 45 } 46 } 47 } 48 49 public class Result 50 { 51 public string Title { get; set; } 52 public string Content { get; set; } 53 }
时间: 2024-10-15 03:39:09