jQuery、Ajax,DataTable数据如何转换成Json格式

在使用JQery的Ajax功能时经常要获取数据,而Net中获取的数据经常方便的就是DataTable

而JQuery要Json格式:这样就是转换可以利用以下这个方法进行

 /// <summary>
    /// DataTable转成Json数据
    /// </summary>
    public static class DataTableToJSON
    {
        /// <summary>
        /// 将dt转化成Json数据 格式如 table[{id:1,title:'体育'},id:2,title:'娱乐'}]
        /// </summary>
        /// <param name="dt"></param>
        /// <returns></returns>
        public static string DtToSON(DataTable dt)
        {
            StringBuilder jsonBuilder = new StringBuilder();
            jsonBuilder.Append("recordcount:" + dt.Rows.Count + ",table: [");
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                if (i > 0)
                    jsonBuilder.Append(",");
                jsonBuilder.Append("{");
                for (int j = 0; j < dt.Columns.Count; j++)
                {
                    if (j > 0)
                        jsonBuilder.Append(",");
                    jsonBuilder.Append(dt.Columns[j].ColumnName.ToLower() + ": '" + dt.Rows[i][j].ToString().Replace("\t", " ").Replace("\r", " ").Replace("\n", " ").Replace("\'", "\\\'") + "'");
                }
                jsonBuilder.Append("}");
            }
            jsonBuilder.Append("]");
            return jsonBuilder.ToString();
        }
    }

/////////////////////////////////////////////前台jqery如何使用请看下面的实现方法//////////////////////////////////////////////////

前台页面

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="ClassNameByJSON.aspx.cs" Inherits="ClassName" %>

<!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 runat="server">
    <title>无标题页</title>
    <script language="javascript" type="text/javascript" src="js/jquery-1.3.2.min.js"></script>
    <script language="javascript" type="text/javascript">
        $(function(){
            $("#DropDownList1").change(function(){
                 //获取值测试
                // alert($("#DropDownList1").val());
                //ajax获取数据
                $("#DropDownList2").html("");
                $("#DropDownList2").append("<option value=\"0\">--请选择学生--</option>");
                $.get("GetStudent.ashx",{action:"get",className:$("#DropDownList1").val()},function(data){
                //服务器处理后执行,数据由data传回
                var jsJosn=eval('('+data+')');
                //alert(jsJosn.stuentscount);
                //alert(jsJosn.stuents[0].stuName);
              
                for(var i=0;i<jsJosn.stuentscount;i++){
                     $("#DropDownList2").append("<option value=\""+jsJosn.stuents[i].id+"\">"+jsJosn.stuents[i].stuName+"</option>");
                }
   });
            });
        });
    </script>
</head>
<body>
     <form id="form1" runat="server">
    <div>
        <asp:DropDownList ID="DropDownList1" runat="server" DataSourceID="SqlDataSource1"
            DataTextField="ClassName" DataValueField="Id" Width="183px"  AppendDataBoundItems="True">
            <asp:ListItem Value="0">--请选择班级--</asp:ListItem>
        </asp:DropDownList><asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:AjaxDemoConnectionString %>"
            SelectCommand="SELECT * FROM [ClassInfo]"></asp:SqlDataSource>
        <asp:DropDownList ID="DropDownList2" runat="server" AppendDataBoundItems="True" Width="168px">
            <asp:ListItem Value="0">-请选择学生-</asp:ListItem>
        </asp:DropDownList></div>
    </form>
</body>
</html>

获取数据利用.ashx文件

<%@ WebHandler Language="C#" class="GetStudent" %>

using System;
using System.Web;
using System.Data.SqlClient;
using System.Data;
using System.Text;
public class GetStudent : IHttpHandler {
    //通过请求获取学生,返回json对象
   public void ProcessRequest (HttpContext context)     {
       string classVale = context.Request.Params["className"];
       SqlConnection sqlconn = new SqlConnection();
       sqlconn.ConnectionString = @"server=CB2E66F752294E9\SQLEXPRESS;database=ajaxdemo;uid=sa;pwd=sa";
       SqlCommand sqlcomm = new SqlCommand();
       sqlcomm.Connection = sqlconn;
       sqlcomm.CommandText = "select * from dbo.StudentInfo where ClassId=" + int.Parse(classVale);
       SqlDataAdapter adp = new SqlDataAdapter(sqlcomm);
       DataSet set = new DataSet();
       adp.Fill(set);
       //包装成JSON格式
       //例如:{stuentscount:10,stuents:[{id:1,stuName:"张三"},{id:2,stuName:"李四"}]}
       if (set.Tables[0].Rows.Count == 0)
       {
           context.Response.Write("0");
       }
       else
       {
           StringBuilder sb = new StringBuilder();
           sb.Append("{stuentscount:"+set.Tables[0].Rows.Count+",stuents:[");
           for (int i = 0; i < set.Tables[0].Rows.Count; i++)
           {
               sb.Append("{id:" + set.Tables[0].Rows[i]["Id"].ToString() + ",stuName:\""+set.Tables[0].Rows[i]["StudentName"].ToString()+"\"}");
               if (i != set.Tables[0].Rows.Count - 1) {
                   sb.Append(",");
               }
           }
           sb.Append("]}");
           context.Response.Write(sb.ToString());
       }
    }
 
    public bool IsReusable {
        get {
            return false;
        }
    }

}

posted @ 2012-11-05 16:15  Nina  阅读(2336)  评论(1编辑  收藏  举报