Jquery Ajax ashx DataTable 傳參 擷取參數 C#

來源:互聯網
上載者:User
aspx:
在前台頁面中引用jquery,那個版本的都行
<script src="../JS/jquery-1.7.2.js" type="text/javascript"></script>

加入一個按鈕
<input type="button" value="button" id="btn"/> 

 

 js 檔案如下

$(document).ready(function () {
                $.ajax({
                    url: '../Handler.ashx?action=GetProvince', //url  action是方法的名稱
                    data: {id:"11"},//參數
                    type: 'POST',
                    dataType: "text",//可以是text,如果用text,返回的結果為字串;如果需要json格式的,可是設定為json
                    ContentType: "application/json; charset=utf-8",
                    success: function (data) {
                        alert(data);
                        var obj = eval("(" + data + ")");//將字串轉為json
                        alert(obj);
                        alert(obj.T_blog[0].name);
                    },
                    error: function (msg) {
                        alert("失敗");
                    }
                });
    });
});

 Handler.ashx 檔案如下:

<%@ WebHandler Language="C#" Class="Handler" %>

using System;
using System.Data;
using System.Text;
using System.Web;

public class Handler : IHttpHandler {

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

        string method = context.Request["action"];//action
        switch (method)
        {
            case "GetProvince":
                {
                    string a = context.Request.Params["id"];//前台傳過來的參數為id
                    context.Response.Write(GetProvince());
                    break;
                }
            default:
                break;
        }
    }

    public bool IsReusable {
        get {
            return false;
        }
    }
    /// <summary>
    /// 前台需要調用的方法
    /// </summary>
    /// <returns></returns>
    public string GetProvince()
    {
        //TreeViewCommon treeViewCommon= new TreeViewCommon();
        //return treeViewCommon.GetProvince();

        return CreateJsonParameters(GetTable());
    }

    /// <summary>
    /// DataTable
    /// </summary>
    /// <returns></returns>
    public DataTable GetTable()
    {
        DataTable dt = new DataTable();
        dt.Columns.AddRange(new DataColumn[]
                                {
                                    new DataColumn("name",Type.GetType("System.String")), 
                                    new DataColumn("age",Type.GetType("System.Int32"))
                                });
        DataRow dr;
        dr = dt.NewRow();
        dr["name"] = "zhangsan";
        dr["age"] = 10;
        dt.Rows.Add(dr);

        dr = dt.NewRow();
        dr["name"] = "lisi";
        dr["age"] = 15;
        dt.Rows.Add(dr);

        return dt;
    }
    /// <summary>
    /// DataTable 轉 Json
    /// </summary>
    /// <param name="dt"></param>
    /// <returns></returns>
    public static string CreateJsonParameters(DataTable dt)
    {
        /**/
        /**/
        /**/
        /* /****************************************************************************
      * Without goingin to the depth of the functioning of this Method, i will try to give an overview
      * As soon as this method gets a DataTable it starts to convert it into JSON String,
      * it takes each row and in each row it grabs the cell name and its data.
      * This kind of JSON is very usefull when developer have to have Column name of the .
      * Values Can be Access on clien in this way. OBJ.HEAD[0].<ColumnName>
      * NOTE: One negative point. by this method user will not be able to call any cell by its index.
     * *************************************************************************/
        StringBuilder JsonString = new StringBuilder();
        //Exception Handling        
        if (dt != null && dt.Rows.Count > 0)
        {
            JsonString.Append("{ ");
            JsonString.Append("\"T_blog\":[ ");
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                JsonString.Append("{ ");
                for (int j = 0; j < dt.Columns.Count; j++)
                {
                    if (j < dt.Columns.Count - 1)
                    {
                        JsonString.Append("\"" + dt.Columns[j].ColumnName.ToString() + "\":" + "\"" + dt.Rows[i][j].ToString() + "\",");
                    }
                    else if (j == dt.Columns.Count - 1)
                    {
                        JsonString.Append("\"" + dt.Columns[j].ColumnName.ToString() + "\":" + "\"" + dt.Rows[i][j].ToString() + "\"");
                    }
                }
                /**/
                /**/
                /**/
                /*end Of String*/
                if (i == dt.Rows.Count - 1)
                {
                    JsonString.Append("} ");
                }
                else
                {
                    JsonString.Append("}, ");
                }
            }
            JsonString.Append("]}");
            return JsonString.ToString();
        }
        else
        {
            return null;
        }
    }

}

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.