2

我正在尝试使用 AJAX 从数据库中获取一些值,但是每次检查 firebug 时,我都会看到 html 副本。

 function foo() {
            $.ajax({
                type: "POST",
                url: "cssAttempt3.aspx/ConvertDataTabletoString",
                data: {},
                dataType: 'json',
                success: function (response) {
                    console.log(result);
                    //I have tried a bunch of things here.
                    //console.log(response, response[0], response[0].value, 
                    //JSON.parse('<%=ConvertDataTabletoString() %>'), JSON.parse(response), JSON.stringify(response), and the list goes on.
                    //Every single time, Firebug shoots back the html document.
                    //Nothing really stands out in this html document.  No errors.
                    //But time to time, Firebug will say unidentified character
                    //JSON.parse: unexpected character
                    //Line 4
                    //Which can't be right, I'm using Google's jQuery and the console.log below is parsed correctly.
                    //If you look up there, result and response are two different things
                    //But Firebug won't report any error even when I compile that.
                    //I've even typed alert("ASDFSAOF") just to see what happens.  Nothing.
                    //I haven't seen "Fail" either.
                },
                failure: function () {
                    console.log("Fail");
                }
            });
        };

        foo();
        console.log(JSON.parse('<%=ConvertDataTabletoString() %>'));
        //This, which has nothing to do with AJAX, works okay.
        //I've taken from the html document 
    </script>

我重新编辑了这个,因为我认为它不是 JSON。我很抱歉以这种方式引导大家。

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Runtime.Serialization;
public partial class cssAttempt3 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
    }
    // This method is used to convert datatable to json string
    [System.Web.Services.WebMethod]
    public static string ConvertDataTabletoString()
    {
        DataTable dt = new DataTable();
        using (SqlConnection con = new SqlConnection(@"Data Source=localhost\SQLEXPRESS;Initial Catalog=personnet;Integrated Security=Yes;"))
        {
            using (SqlCommand cmd = new SqlCommand(@"SELECT TOP 200 * FROM personnet.dbo.accordionTest", con))
            {
                con.Open();
                SqlDataAdapter da = new SqlDataAdapter(cmd);
                da.Fill(dt);
                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);
                }
                return serializer.Serialize(rows);
            }
        }
    }
}
4

3 回答 3

1

从您的示例和评论中,您的 JSON 可能无效。您可以在JSONLint验证您的输出。如果您展示了如何在cssAttempt3.aspx/ConvertDataTabletoString.

另一个问题是您使用JSON.parse的是JSON.stringify.

JSON.parse将字符串解析为 JSON。

相反,JSON.stringify接受一个值以转换为 JSON 字符串。您的值 ( response) 已经是 JSON。

function foo() {
     $.ajax({
         type: 'POST',
         url: 'cssAttempt3.aspx/ConvertDataTabletoString',
         dataType: 'json',
         contentType: "application/json; charset=utf-8",
         success: function (response) {
             var t = JSON.stringify(response);
             var o = JSON.parse(t); //now this should work. Turns it back into what you get from url response.
             console.log(t);
         },
         failure: function () {
             console.log("Fail");
         },
         error: function (jqXHR,textStatus,errorThrown) {
             console.log(errorThrown); //...its possibly not even JSON response at all!
         }
     });
}

另一方面,创建 JSON 的更有效方法是使用 ASHX 处理程序......并且只需对代码进行少量修改:

[DataContract]将and添加[DataMember]到您的课程中(您需要System.Runtime.Serialization对此进行参考):

[DataContract]
public class MyDataTableClass
{
    [DataMember]
    private string pro;
    [DataMember]
    private string sn;
    [DataMember]
    private string po;
    //etc

然后制作 ASHX(右键单击您的项目 -> 添加新项目 -> 通用处理程序):

public class ConvertDataTabletoString: IHttpHandler
{     
    public void ProcessRequest(HttpContext context)
    {
        List<MyDataTableClass> m = //populate

        MemoryStream stream = new MemoryStream();
        DataContractJsonSerializer s = new DataContractJsonSerializer(typeof(List<MyDataTableClass>));
        s.WriteObject(stream, m);
        stream.Position = 0;
        StreamReader sr = new StreamReader(stream);

        context.Response.ContentType = "application/json";
        context.Response.Write(sr.ReadToEnd());
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
}

然后只需更新您的网址:url: 'ConvertDataTabletoString.ashx',

于 2013-10-01T13:02:53.520 回答
1

你确定用or属性标记你的ConvertDataTabletoString方法了吗?[WebMethod][ScriptMethod]

如果您不这样做,那么当您通过 Ajax 请求页面时,它只会被处理,就好像您通过正常的 HTTP GET 请求请求它一样,并且 aspx 页面生成的实际 HTML 将返回给您。这就是似乎正在发生的事情,尽管我当然可能是错的。

此外,我通常更喜欢在 aspx 页面上创建我想通过 Ajax 调用的方法,static因为这清楚地表明它们不是“正常”aspx 页面的一部分(如果你没有混合功能并且这个 aspx 页面只存在于服务 AJAX 请求然后它可能没问题)

编辑:忘了提及,请确保您仔细阅读了在 firebug 中显示的 HTML——它实际上可能是一个 Web 服务器错误消息页面,表明其他事情完全是错误的!

于 2013-10-01T12:44:02.323 回答
0

在您的成功函数中,您传递响应变量。此变量是您从服务器获得的响应的存储(包括值)。

所以尝试以下:

    function foo() {
    $.ajax({
        type: "POST",
        url: "cssAttempt3.aspx/ConvertDataTabletoString",
        data: {},
        dataType: 'jsonp',
        success: function (response) {

            console.log(response); //change the parse parameter to response
        },
        failure: function () {
            console.log("Fail");
        }
    });
};

编辑:

尝试使用 jsonp 作为数据类型并在不解析的情况下记录输出(jsonp 为您解析)

示例更新。

编辑 2:使用json.net

using Newtonsoft.Json;
List<Dictionary<string, string>> testDictionary = new List<Dictionary<string, string>()>();
string json = JsonConvert.SerializeObject(testDictionary);

学分: C# List<dictionary> To Json

于 2013-10-01T12:43:53.933 回答