020-Json结构数据序列化异步传递

时间:2022-01-14 17:00:20

C#中将.Net对象序列化为Json字符串的方法:

JavaScriptSerializer().Serialize(p),
JavaScriptSerializer在System.Web.Extensions.dll中,
是.Net3.x 中新增的类。
完整:System.Web.Script.Serialization.JavaScriptSerializer

FormTest.html

 <!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
<script src="js/jquery-1.7.1.min.js"></script>
<script>
$(function () {
$('#btnAdd').click(function () {
//$.post('FormTest.ashx',
// //'title=' + $('#title').val()+'&content='+$('#content').val(),
// //$('#form1').serialize(),//返回由name与value构成的键值对字符串
// $('#form1').serializeArray(),//由name与value构成的json对象的数组
// function(msg) {
// $('#showDiv').html(msg);
// }
//); //$.getJSON(
// 'FormTest.ashx',
// $('#form1').serialize(),
// function (data) {//{Title:***,Content:***}
// //{"Title":"xlb","Content":"yg"}
// $('#showDiv').html('title:'+data.Title+'<br>content:'+data.Content);
// }
//); $.getJSON(
'FormTest.ashx',
$('#form1').serializeArray(),
function (data) {//[{},{},{}....{}]
var list = $('#showDiv table');
$.each(data, function (index, item) {
list.append('<tr>' +
'<td>' + item.Title + '</td>' +
'<td>' + item.Content + '</td>' +
'</tr>');
});
}
);
});
});
</script> </head>
<body>
<form id="form1">
<input type="text" id="title" name="title" />
<br />
<input type="text" id="content" name="content" />
<br />
<input type="button" id="btnAdd" value="添加" />
</form>
<div id="showDiv">
<table border="1"></table>
</div>
</body>
</html>

FormTest.ashx

     public class FormTest : IHttpHandler
{ public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain"; string title = context.Request["title"];
string content = context.Request["content"]; //context.Response.Write(title+"-"+content); #region 返回单一对象
//Result result=new Result();
//result.Title = title;
//result.Content = content; //JavaScriptSerializer js=new JavaScriptSerializer();
//string result1 = js.Serialize(result);
//context.Response.Write(result1);
#endregion #region 返回数组
List<Result> list = new List<Result>();
for (int i = ; i < ; i++)
{
list.Add(new Result()
{
Title = title + i,
Content = content + i
});
} JavaScriptSerializer js = new JavaScriptSerializer();
string result = js.Serialize(list);
context.Response.Write(result);
#endregion
} public bool IsReusable
{
get
{
return false;
}
}
} public class Result
{
public string Title { get; set; }
public string Content { get; set; }
}