jQuery 得到 ashx 返回的 JSON 格式的 DataSet 的方法

对于代码中要注意的问题,已经添加了注释。

ASPX 代码

Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/

--><%@ Page Language="C#"%>
<!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>dotnet.aspx.cc jQuery 测试</title>
  
<script src="jquery-1.6.2.min.js" type="text/javascript"></script>
  
<script type="text/javascript">
    
function getData() {
      $(
"#data").val("");
      jQuery.post(
GetList.ashx, {}, function (data) {
        
var obj = JSON.parse(data);
        $.each(obj.Tables,
function (index, table) {
          
//根据不同的表名,显示不同的字段。得到特定表,table = obj.Tables[1]
          var tableName = table.Name;
          $.each(table.Rows,
function (index, row) {
            
if (tableName =="BlogArticle")
              $(
"#data").val($("#data").val() + row.Title +"\r\n");
            
else
              $(
"#data").val($("#data").val() + row.UserName +"\r\n");
          });
        });
      })
    }
  
</script>
</head>
<body>
  
<form id="form1" runat="server">
  
<textarea id="data" style="width: 200px; height: 500px"></textarea>
  
<input type="button" value="得到数据" onclick="getData()"/>
  
</form>
</body>
</html>
ASHX 代码

Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/

--><%@ WebHandler Language="C#" Class="GetList"%>

using System;
using System.Web;
using System.Text;
using System.Collections.Generic;
using System.Collections;
using System.Web.Script.Serialization;

public class GetList : IHttpHandler
{

  public void ProcessRequest(HttpContext context)
  {
    context.Response.ContentType = "text/plain";
    context.Response.Write(this.GetDataSet());
  }

  public bool IsReusable
  {
    get
    {
      return false;
    }
  }
  private String GetDataSet()
  {
    //测试用数据
    System.Data.DataSet ds = new System.Data.DataSet();
    System.Data.DataTable dataTable1 = new System.Data.DataTable("BlogUser");
    System.Data.DataRow dr;
    dataTable1.Columns.Add(new System.Data.DataColumn("UserId", typeof(System.Int32)));
    dataTable1.Columns.Add(new System.Data.DataColumn("UserName", typeof(System.String)));
    dataTable1.PrimaryKey = new System.Data.DataColumn[] { dataTable1.Columns["UserId"] };

    for (int i = 0; i
< 8; i++)
    {
      dr
= dataTable1.NewRow();
      
dr[0] = i;
      
dr[1] = "\"[<>{}],【孟子E章】" + i.ToString(); //特殊字符的测试
      dataTable1.Rows.Add(dr);
    }
    System.Data.DataTable dataTable2 = new System.Data.DataTable("BlogArticle");
    dataTable2.Columns.Add(new System.Data.DataColumn("ArticleId", typeof(System.Int32)));
    dataTable2.Columns.Add(new System.Data.DataColumn("Title", typeof(System.String)));
    dataTable2.Columns.Add(new System.Data.DataColumn("UserId", typeof(System.Int32)));
    dataTable2.PrimaryKey = new System.Data.DataColumn[] { dataTable1.Columns["ArticleId"] };
    Random rd = new Random();
    for (int i = 0; i
< 20; i++)
    {
      dr
= dataTable2.NewRow();
      
dr[0] = i;
      
dr[1] = "文章标题" + i.ToString();
      dr[2]
= rd.Next(0, 7);
      dataTable2.Rows.Add(dr);
    }
    ds.Tables.Add(dataTable1);
    ds.Tables.Add(dataTable2);
    return Dataset2Json(ds);

  }

  /// <summary
>  
  /// dataTable转换成Json格式  
  ///
</summary>  
  ///
<param name="dt"></param>  
  ///
<returns></returns>  
  public static string DataTable2Json(System.Data.DataTable dt)
  {
    StringBuilder jsonBuilder = new StringBuilder();
    jsonBuilder.Append("{\"Name\":\"" + dt.TableName + "\",\"Rows");
    jsonBuilder.Append("\":[");
    for (int i = 0; i
< dt.Rows.Count; i++)
    {
      jsonBuilder.Append("{");
      for (int j
= 0; j < dt.Columns.Count; j++)
      {
        jsonBuilder.Append("\"");
        jsonBuilder.Append(dt.Columns[j].ColumnName);
        jsonBuilder.Append("\":\"");
        jsonBuilder.Append(dt.Rows[i][j].ToString().Replace("\"","\\\"")); //对于特殊字符,还应该进行特别的处理。
        jsonBuilder.Append("\",");
      }
      jsonBuilder.Remove(jsonBuilder.Length - 1, 1);
      jsonBuilder.Append("},");
    }
    jsonBuilder.Remove(jsonBuilder.Length - 1, 1);
    jsonBuilder.Append("]");
    jsonBuilder.Append("}");
    return jsonBuilder.ToString();
  }

  /// <summary
>  
  /// DataSet转换成Json格式  
  ///
</summary>  
  ///
<param name="ds">DataSet</param>  
  ///
<returns></returns>  
  public static string Dataset2Json(System.Data.DataSet ds)
  {
    StringBuilder json = new StringBuilder();
    json.Append("{\"Tables\":");
    json.Append("[");
    foreach (System.Data.DataTable dt in ds.Tables)
    {
      json.Append(DataTable2Json(dt));
      json.Append(",");
    }
    json.Remove(json.Length - 1, 1);
    json.Append("]");
    json.Append("}");
    return json.ToString();
  }
}

网上有DataSet转JSON格式的方法,是错误的,比如下面的这个,返回的格式搜有问题的,表的数据直接没有任何分割,所以不能使用 JavaScript 正确地解析。

C# 代码

Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/

-->    #region dataTable转换成Json格式  
    
///<summary>  
    
/// dataTable转换成Json格式  
    
///</summary>  
    
///<param name="dt"></param>  
    
///<returns></returns>  
    publicstaticstring DataTable2Json(DataTable dt)  
    {  
        StringBuilder jsonBuilder
=new StringBuilder();  
        jsonBuilder.Append(
"{\"");  
        jsonBuilder.Append(dt.TableName.ToString());  
        jsonBuilder.Append(
"\":[");  
        
for (int i =0; i < dt.Rows.Count; i++)  
        {  
            jsonBuilder.Append(
"{");  
            
for (int j =0; j < dt.Columns.Count; j++)  
            {  
                jsonBuilder.Append(
"\"");  
                jsonBuilder.Append(dt.Columns[j].ColumnName);  
                jsonBuilder.Append(
"\":\"");  
                jsonBuilder.Append(dt.Rows[i][j].ToString());  
                jsonBuilder.Append(
"\",");  
            }  
            jsonBuilder.Remove(jsonBuilder.Length
-1, 1);  
            jsonBuilder.Append(
"},");  
        }  
        jsonBuilder.Remove(jsonBuilder.Length
-1, 1);  
        jsonBuilder.Append(
"]");  
        jsonBuilder.Append(
"}");  
        
return jsonBuilder.ToString();  
    }  
    
    
#endregion dataTable转换成Json格式  
    
    
#region DataSet转换成Json格式  
    
///<summary>  
    
/// DataSet转换成Json格式  
    
///</summary>  
    
///<param name="ds">DataSet</param>  
    
///<returns></returns>  
    publicstaticstring Dataset2Json(DataSet ds)  
    {  
        StringBuilder json
=new StringBuilder();  
          
        
foreach (DataTable dt in ds.Tables)  
        {  
            json.Append(
"{\"");  
            json.Append(dt.TableName);  
            json.Append(
"\":");  
            json.Append(DataTable2Json(dt));  
            json.Append(
"}");  
        }  
        
return json.ToString();  
    }  
    
#endregion
posted @ 2012-01-16 14:55  殇伈de錑婲  阅读(669)  评论(0编辑  收藏  举报