jQuery、Ajax,DataTable資料如何轉換成Json格式

來源:互聯網
上載者:User

在使用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;
        }
    }

}

#Jquery
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.