[开发知识点] 使用JQuery 将DataTable 转化成JSON数据,前端无法处理JSON数据的注意事项

 protected void Page_Load(object sender, EventArgs e)
    {
        if (Request["action"] != null)
        {
            DataTable dt = this.myData();
            string result="";
            string s = DataTableToJson(result, dt);
            Response.Write(s);
            Response.End();
        }
    }
    public DataTable myData()
    {
        DataTable dt = new DataTable();
        DataColumn dc;
        DataRow dr;

        dc = new DataColumn("Name", System.Type.GetType("System.String"));
        dt.Columns.Add(dc);
        dc = new DataColumn("Email", System.Type.GetType("System.String"));
        dt.Columns.Add(dc);
        dc = new DataColumn("Phon", System.Type.GetType("System.String"));
        dt.Columns.Add(dc);
        dc = new DataColumn("Move", System.Type.GetType("System.String"));
        dt.Columns.Add(dc);
        dc = new DataColumn("Pan", System.Type.GetType("System.String"));
        dt.Columns.Add(dc);
        dc = new DataColumn("select", System.Type.GetType("System.String"));
        dt.Columns.Add(dc);
        for (int i = 1; i < 7; i++)
        {
            dr = dt.NewRow();
            dr["Name"] = "Name" + i.ToString();
            dr["Email"] = "Email" + i.ToString();
            dr["Phon"] = "Phon" + i.ToString();
            dr["Move"] = "Move" + i.ToString();
            dr["Pan"] = "Pan" + i.ToString();
            dr["select"] = i.ToString();
            dt.Rows.Add(dr);
        }

        int count = dt.Rows.Count;
        return dt;
    }

    //将datatable数据转换成JSON数据
    public string DataTableToJson(string jsonName, DataTable dt)
    {
        StringBuilder Json = new StringBuilder();
        Json.Append("[");
        if (dt.Rows.Count > 0)
        {
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                Json.Append("{");
                for (int j = 0; j < dt.Columns.Count; j++)
                {
                    Json.Append(dt.Columns[j].ColumnName.ToString() + ":\"" + dt.Rows[i][j].ToString() + "\"");
                    if (j < dt.Columns.Count - 1)
                    {
                        Json.Append(",");
                    }
                }
                Json.Append("}");
                if (i < dt.Rows.Count - 1)
                {
                    Json.Append(",");
                }
            }
        }
        Json.Append("]");
        return Json.ToString();
    }
//前端的JavaScript代码
var jsondata=[{a:11,b:12}];
$(document).ready(function(){
$.post("testdemo2.aspx",{action:"demo",mdata:"1"},function(data){
var jsondata=eval(data); //这句话是非常关键的,否在返回的data无法处理
$.each(jsondata,function(index,entry)
{
    alert(entry.Move);
});
//window.alert(data);

});
}
);
posted @ 2010-07-05 12:21  老高dotnet实践  阅读(1759)  评论(1编辑  收藏  举报