【问题标题】:Am I not returning this JSON string correctly?我没有正确返回这个 JSON 字符串吗?
【发布时间】:2013-10-07 14:59:31
【问题描述】:

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

【问题讨论】:

  • 您完全忽略了 response 而是 console.log()ing 一个服务器端值。为什么?
  • console.log(JSON.parse(response)) 告诉你什么?
  • 我在下面提到我已经尝试过几次响应。 JSON.parse 只是我最近的尝试。我正在使用 console.log 来查看是否出现任何问题。
  • console.log(JSON.parse(response)) 告诉我同样的事情。只显示我的网站。
  • 你也可以在firebug中查看网络状态。查看您是否正在通过服务器接收数据。

标签: asp.net jquery


【解决方案1】:

根据您的示例和 cmets,您的 JSON 可能无效。您可以在JSONLint 验证您的输出。如果您在 cssAttempt3.aspx/ConvertDataTabletoString 上展示您是如何创建 JSON 提要的,那将非常有帮助。

另一个问题是您使用的是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(右键单击您的项目 -> 添加新项 -> 通用处理程序):

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

【讨论】:

  • 我是 ashx 概念的新手。我已将命名空间 MyTypes {[DataContract//etc 添加到我的 cs 文件并添加了 ashx 文件,但出现了很多错误“找不到类型或命名空间...”
  • 我在 JSONLint 验证了我的 JSON。除了周围的撇号(我试图排除它们;结果相同)之外,它是有效的。
  • 你需要using System.Runtime.Serialization
  • 另外...您说您验证了您的 JSON,但您发布的一些内容无效,并且在其他 cmets 中您说响应正在为您的网站带回 HTML...所以不清楚什么是真的发生了。
  • 我很抱歉造成混乱。 foo() 的响应是 html,它看不到 JSON。我做了一个没有任何 AJAX 的 console.log() 可以清楚地看到和解析 JSON。我将 firebug 的 console.log() 复制并粘贴到 JSONLint 中,由于它周围有撇号,它是无效的。除了撇号,它是有效的。 Firebug 同时报告 foo() 和 console.log(),我想让 foo() 工作。
【解决方案2】:

您是否确定用[WebMethod][ScriptMethod] 属性标记您的ConvertDataTabletoString 方法?

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

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

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

【讨论】:

  • 我在代码前添加了 [System.Web.Services.WebMethod]。我还查看了 html,但没有任何内容出现在我身上。我认为不会有任何事情,因为我正在做 console.log 和 alert()。
  • 酷。如果您仍然遇到问题,您可以发布一些您在 Firebug 中看到的 HTML 吗?
【解决方案3】:

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

所以请尝试以下操作:

    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

【讨论】:

  • Marcel 早些时候向我建议过,我得到了相同的结果。
  • 你能把这个的萤火虫输出贴出来吗?
  • 我已将其更改为 jsonp 和 console.log(response),但它仍然会发布 html。我将发布 C# 代码并希望它提供一些见解。
  • 结果相同,但我认为我做得不对。我安装了 Json.net 并应用了上述更改(我的问题帖子在 ATTEMPT 下反映了这一点:)。你能看到吗?
  • 是否可以发布 c# 应用程序的返回字符串而不是 ajax 返回?那么这个 json 字符串是否正确?
猜你喜欢
  • 2014-06-14
  • 2015-01-11
  • 1970-01-01
  • 2013-10-12
  • 1970-01-01
  • 2016-08-21
  • 1970-01-01
  • 1970-01-01
  • 2012-08-07
相关资源
最近更新 更多