如何序列化并将json字符串发送回Ajax函数。 [英] How do I serialize and send a json string back to an Ajax function.

查看:65
本文介绍了如何序列化并将json字符串发送回Ajax函数。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试序列化并将json字符串发送回Ajax函数。我收到错误:

I am trying to serialize and send a json string back to an Ajax function. I am getting an error in:

dt = ds.Tables[0];







[System.Web.Services.WebMethod]
        public static string GetJSONdata(string id1)
        {
            DataSet ds;
            string connStr = ConfigurationManager.ConnectionStrings["jsonobject"].ConnectionString;
            string cmdStr = "SELECT ([datetime],[col1],[col2],[col3]) FROM [jsondata] WHERE [idd]=@idd;";
            try
            {
                using (SqlConnection conn = new SqlConnection(connStr))
                {
                    using (SqlCommand cmd = new SqlCommand(cmdStr, conn))
                    {
                        conn.Open();
                        cmd.Parameters.AddWithValue("@idd", id1);
                        cmd.ExecuteNonQuery();
                        using (SqlDataAdapter da = new SqlDataAdapter(cmd))
                        {
                            da.Fill(ds);
                            dt = ds.Tables[0];
                        }
                    }
                }
            }
            catch (Exception ex)
            {

            }
            System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
            List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
            Dictionary<string, object> row;
            foreach (DataRow dr in dt.Rows)
            {
                row = new Dictionary<string, object>();
                foreach (DataColumn col in dt.Columns)
                {
                    row.Add(col.ColumnName, dr[col]);
                }
                rows.Add(row);
            }
            var json2 = serializer.Serialize(rows);
            return json2;
        }

推荐答案

更改代码...

Change the code...
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
    da.Fill(ds);
    dt = ds.Tables[0];
}



要...


To...

DataTable dt = null;

using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
    da.Fill(ds);
}

if(ds != null && ds.Tables != null && ds.Tables.Count > 0)
{
    dt = ds.Tables[0];
}



现在检查 dt 是否 null 与否。如果不是 null ,那么继续并序列化。


Now check if dt is null or not. If not null, then proceed and serialize that.


这篇关于如何序列化并将json字符串发送回Ajax函数。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆