我没有正确返回这个JSON字符串吗?

时间:2013-10-01 12:37:42

标签: asp.net jquery

我正在尝试使用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);
            }
        }
    }
}

3 个答案:

答案 0 :(得分:1)

您是否确保使用ConvertDataTabletoString[WebMethod]属性标记了[ScriptMethod]方法?

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

此外,我通常更喜欢在aspx页面static上创建我想通过Ajax调用的方法,因为这清楚地表明它们不属于&#34; normal&#34; aspx页面(如果你没有混合功能,这个aspx页面只存在于服务AJAX请求,那么它可能没问题)

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

答案 1 :(得分:1)

从您的示例和评论中,您的JSON可能无效。您可以在JSONLint验证输出。如果您在cssAttempt3.aspx/ConvertDataTabletoString展示了如何创建JSON Feed,那将非常有用。

另一个问题是您使用的是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][DataMember]添加到您的班级(您需要System.Runtime.Serialization的引用才能实现此目的):

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

然后制作ASHX(右键单击您的项目 - &gt;添加新项目 - &gt; Generic Handler):

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',

答案 2 :(得分: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