0

我正在尝试从 SQL 服务器数据库中检索数据并将其转换为 JSON 并尝试使用 JQuery Ajax 函数显示 json 数据,这是 C# 代码,

C#

public String GetData()
{
    try
    {
        String strjson;               
        string connectionstring = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
        SqlConnection Con = new SqlConnection(connectionstring);
        DataSet DS = new DataSet();
        String CmdText = "Select Compname,compadd1,compadd2,compemail from company where compid=@cmpid";
        SqlCommand cmd = new SqlCommand(CmdText, Con);
        cmd.Parameters.Add("@cmpid", SqlDbType.Int).Value = 22;
        Con.Open();
        SqlDataAdapter DA = new SqlDataAdapter(cmd);
        DA.Fill(DS);           
        DataTable dTable = DS.Tables[0];
        strjson = GetJSONString(dTable);
        Con.Close();
        return strjson;
    }
    catch (Exception ex)
    {
        throw new System.Exception("Error In Get Data" + ex.Message);
    }
} 

GetJSONString(dTable) 函数工作正常,这里是 JQuery 代码,

jQuery 和 HTML

    <form id="form1" runat="server">
    <div>
        <h1>JSON Sample</h1>
        <button id="getdata">Get Data</button>
        <div id="company"></div>
<%--        <asp:Button ID="aspbutton" runat="server" Text=".Net Call" OnClick="btnOn_Click" />
        <asp:GridView runat="server" ID="grdview"></asp:GridView>--%>
    </div>
    <script type="text/javascript">        
        $(document).ready(function () {
            $("#getdata").click(function () {                
                $.ajax({
                    type: "POST",
                    contentType: "application/json; charset=utf-8",
                    data: "",
                    url: "Default.aspx/GetData",
                    dataType: "json",
                    success: function (data) {
                        alert(data.d);
                        $("#company").html(data.d);
                    }
                });
            });
        });
    </script>
    </form>

我已经包含了 jQuery 文件,如果我犯了任何错误,请告诉我,

编辑:GetJSONString 添加

公共静态字符串 GetJSONString(DataTable Dt) { string[] StrDc = new string[Dt.Columns.Count]; 字符串 HeadStr = string.Empty;

    for (int i = 0; i < Dt.Columns.Count; i++)
    {
        StrDc[i] = Dt.Columns[i].Caption;
        HeadStr += "\"" + StrDc[i] + "\" : \"" + StrDc[i] + i.ToString() + "¾" + "\",";
    }


    HeadStr = HeadStr.Substring(0, HeadStr.Length - 1);


    StringBuilder Sb = new StringBuilder();
    Sb.Append("{\"" + Dt.TableName + "\" : [");


    for (int i = 0; i < Dt.Rows.Count; i++)
    {
        string TempStr = HeadStr;
        Sb.Append("{");


        for (int j = 0; j < Dt.Columns.Count; j++)
        {
            switch (Dt.Columns[j].DataType.ToString())
            {
                case "System.DateTime":
                    DateTime cv = (DateTime)Dt.Rows[i][j];
                    TempStr = TempStr.Replace(Dt.Columns[j] + j.ToString() + "¾", cv.Year + "," + (cv.Month - 1) + "," + cv.Day + "," + cv.Hour + "," + cv.Minute + "," + cv.Second + "," + cv.Millisecond);
                    break;


                case "System.Boolean":
                    TempStr = TempStr.Replace(Dt.Columns[j] + j.ToString() + "¾", Dt.Rows[i][j].ToString().ToLower());
                    break;


                default:
                    string str = Dt.Rows[i][j].ToString();
                    str = str.Replace("\n", "\\\\n");
                    str = str.Replace("\\", "\\\\\\\\");
                    str = str.Replace("\"", "ppp");
                    str = str.Replace("'", "\\\'");
                    str = str.Replace("\r", "\\\\r");


                    TempStr = TempStr.Replace(Dt.Columns[j] + j.ToString() + "¾", str);
                    break;
            }
        }


        Sb.Append(TempStr + "},");
    }


    Sb = new StringBuilder(Sb.ToString().Substring(0, Sb.ToString().Length - 1));
    Sb.Append("]}");


    return Sb.ToString();
}

我在 Ajax 调用中添加了错误:部分,现在收到错误“错误;[对象对象]”

4

1 回答 1

0

最后,我发现了问题所在,我必须"[WebMethod()]"在 asp.net 函数之前添加声明。例如,

    [WebMethod()]
    public static string GetData()
    {

        try
        {
            string strjson;
            string connectionstring = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
            SqlConnection Con = new SqlConnection(connectionstring);
            DataSet DS = new DataSet();
            String CmdText = "Select Compname,compadd1,compadd2,compemail from aas_company where compid=@cmpid";
            SqlCommand cmd = new SqlCommand(CmdText, Con);
            cmd.Parameters.Add("@cmpid", SqlDbType.Int).Value = 22;
            Con.Open();
            SqlDataAdapter DA = new SqlDataAdapter(cmd);
            DA.Fill(DS);
            DataTable dTable = DS.Tables[0];
            strjson = GetJSONString(dTable);
            Con.Close();               
            return strjson;
        }
        catch (Exception ex)
        {
            throw new System.Exception("Error In Get Data" + ex.Message);
        }
    }
于 2013-07-05T17:18:28.967 回答