详谈 Jquery Ajax异步处理Json数据.

2020-05-19 07:27:39易采站长站整理


<%@ WebHandler Language=”C#” Class=”Handler” %>
using System;
using System.Web;
using System.Collections;
using System.Collections.Generic;
using System.Web.Script.Serialization;
public class Handler : IHttpHandler {
public void ProcessRequest (HttpContext context) {
JavaScriptSerializer jss = new JavaScriptSerializer();
context.Response.ContentType = “text/plain”;
// 返回的为Json格式一 Js对象
string data = “{”name”:”wang”,”age”:25}”;
// 返回的为Json格式二 Js数组
//string data = “[{”name”:”wang”,”age”:25},{”name”:”zhang”,”age”:22}]”;
context.Response.Write(data);
}
public bool IsReusable {
get {
return false;
}
}
}

以上基本上就第二种方法,可能有人不喜欢拼字符串.那有什么好办法呢?答案是有.微软对Json有很好的支持.
拿上例子说我们只要把Handler.ashx改一下就可以了
Handler.ashx 代码如下

<%@ WebHandler Language=”C#” Class=”Handler” %>
using System;
using System.Web;
using System.Collections;
using System.Collections.Generic; // Dictionary<,> 键值对集合所需
using System.Web.Script.Serialization; //JavaScriptSerializer 类所需
public class Handler : IHttpHandler {
public void ProcessRequest (HttpContext context) {
JavaScriptSerializer jss = new JavaScriptSerializer();
context.Response.ContentType = “text/plain”;
Dictionary<string, string> drow = new Dictionary<string, string>();
drow.Add(“name”, “Wang”);
drow.Add(“age”, “24”);
context.Response.Write(jss.Serialize(drow));
}
public bool IsReusable {
get {
return false;
}
}
}

ASP.Net中的JavaScriptSerializer为我们提供了很好的方法
jss.Serialize(drow) 是把drow的Dictionary<string, int> (键和值的集合)数据类型转换成Json数据格式
调试结果如下图 (上面例子是输出了一个键值多集合即一个Json形式一的Js对象)



如果要输出Json形式二(Js数组)呢? 我们也只要改动一部分就了


Handler.ashx 代码如下

<%@ WebHandler Language=”C#” Class=”Handler” %>
using System;
using System.Web;
using System.Collections;
using System.Collections.Generic;
using System.Web.Script.Serialization;
public class Handler : IHttpHandler {
public void ProcessRequest (HttpContext context) {
JavaScriptSerializer jss = new JavaScriptSerializer();
context.Response.ContentType = “text/plain”;