Jquery Ajax ashx DataTable 传参 获取参数 C#

复制代码
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;
        }
    }

}
复制代码

 

posted @ 2012-11-05 16:13  Nina  阅读(470)  评论(0编辑  收藏  举报