我不能正确返回这个JSON字符串

我不能正确返回这个JSON字符串

本文介绍了我不能正确返回这个JSON字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

我试图抓住使用AJAX从数据库中的一些值,但每次我检查萤火虫的时候,我看到HTML副本,而不是

 函数foo(){
            $阿贾克斯({
                键入:POST,
                网址:cssAttempt3.aspx / ConvertDataTabletoString
                数据:{},
                数据类型:JSON,
                成功:函数(响应){
                    的console.log(结果);
                    //我在这里尝试了一堆东西。
                    //console.log(response,响应[0],响应[0]。价值,
                    //JSON.parse('<%= ConvertDataTabletoString()%GT;'),JSON.parse(响应),JSON.stringify(响应),和这样的例子不胜枚举。
                    //每一个时间,萤火虫回来拍摄的HTML文档。
                    //没有真正脱颖而出此html文件英寸没有错误。
                    //但是每隔一段时间,将萤火虫说,身分不明的性格
                    //JSON.parse:意外的字符
                    // 4号线
                    //这不可能是正确的,我使用谷歌的jQuery和下面的console.log被正确解析。
                    //如果你看看那里,结果和反应是两回事
                    当我编译//但是萤火虫甚至不会报告任何错误。
                    //我甚至输入警报(ASDFSAOF),只是为了看看会发生什么。没有。
                    //我没有看到失败两种。
                },
                故障:功能(){
                    的console.log(失败);
                }
            });
        };        富();
        的console.log(JSON.parse('<%= ConvertDataTabletoString()%GT;'));
        //这,这无关与AJAX,工作好。
        //我从html文件取
    < / SCRIPT>

我重新编辑这一点,因为我不认为这是JSON。我的道歉领导大家的方式。

 使用系统;
使用System.Collections.Generic;
使用System.Data这;
使用System.Data.SqlClient的;
使用System.Runtime.Serialization;
公共部分类cssAttempt3:System.Web.UI.Page
{
    保护无效的Page_Load(对象发件人,EventArgs的发送)
    {
    }
    //此方法用于数据表转换成JSON字符串
    [System.Web.Services.WebMethod]
    公共静态字符串ConvertDataTabletoString()
    {
        DataTable的DT =新的DataTable();
        使用(SqlConnection的CON =新的SqlConnection(@数据源=本地主机\\ SQLEX $ P $干燥综合征;初始目录= personnet;集成安全性=是;))
        {
            使用(CMD的SqlCommand =新的SqlCommand(@SELECT TOP 200 * FROM personnet.dbo.accordionTestCON))
            {
                con.Open();
                SqlDataAdapter的大=新SqlDataAdapter的(CMD);
                da.Fill(DT);
                System.Web.Script.Serialization.JavaScriptSerializer串行=新System.Web.Script.Serialization.JavaScriptSerializer();
                清单<&字典LT;字符串对象>>行=新的List<&字典LT;字符串对象>>();
                字典<字符串对象>行;
                的foreach(在dt.Rows的DataRow博士)
                {
                    行=新词典与LT;字符串对象>();
                    的foreach(在dt.Columns的DataColumn COL)
                    {
                        row.Add(col.ColumnName,博士[COL]);
                    }
                    rows.Add(行);
                }
                返回serializer.Serialize(行);
            }
        }
    }
}


解决方案

从你的例子和意见,很可能你的JSON是无效的。您可以验证您在输出。它会真正帮助,如果你表现出你是怎样在 cssAttempt3.aspx / ConvertDataTabletoString 创建JSON饲料。

另一个问题是,你正在使用 JSON.parse 而不是 JSON.stringify

<一个href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse?redirectlocale=en-US&redirectslug=JavaScript%2FReference%2FGlobal_Objects%2FJSON%2Fparse\"相对=nofollow> JSON.parse 解析一个的字符串的作为JSON。

相反, JSON.stringify 接受的值转换为JSON字符串。你的价值(响应)已经是JSON。

 函数foo(){
     $阿贾克斯({
         输入:POST,
         网址:'cssAttempt3.aspx / ConvertDataTabletoString',
         数据类型:JSON,
         的contentType:应用/ JSON的;字符集= UTF-8,
         成功:函数(响应){
             VAR T = JSON.stringify(响应);
             变种O = JSON.parse(T); //现在这个应该工作。把它放回你的URL响应得到什么。
             的console.log(T);
         },
         故障:功能(){
             的console.log(失败);
         },
         错误:功能(jqXHR,textStatus,errorThrown){
             的console.log(errorThrown); //...its可能甚至没有JSON响应了!
         }
     });
}

作为边没有,创建JSON更有效的方式是与一个ASHX处理程序...并只需要稍作修改到code:

添加 [DataContract] [数据成员] 到类(你需要参考 System.Runtime.Serialization 这个工作):

  [DataContract]
公共类MyDataTableClass
{
    [数据成员]
    私人串亲;
    [数据成员]
    私人字符串SN;
    [数据成员]
    私人字符串婆;
    //等等

和则会使ASHX(右键单击您的项目 - >添加新项 - >通用处理程序):

 公共类ConvertDataTabletoString:IHttpHandler的
{
    公共无效的ProcessRequest(HttpContext的背景下)
    {
        清单&LT; MyDataTableClass&GT; M = //填充        MemoryStream的流=新的MemoryStream();
        DataContractJsonSerializer S =新DataContractJsonSerializer(typeof运算(列表&LT; MyDataTableClass&GT;));
        s.WriteObject(流,米);
        stream.Position = 0;
        StreamReader的SR =新的StreamReader(流);        context.Response.ContentType =应用/ JSON;
        context.Response.Write(sr.ReadToEnd());
    }    公共BOOL IsReusable
    {
        得到
        {
            返回false;
        }
    }
}

然后就更新你的网址:网​​址:'ConvertDataTabletoString.ashx,

I'm trying to grab some values from the database using AJAX, but every time I check firebug, I see the html copy instead.

 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>

I reedited this, because I do not think it's the JSON. My apologies for leading everyone that way.

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);
            }
        }
    }
}
解决方案

From your examples and comments, it's possible your JSON isn't valid. You can validate your output at JSONLint. It'd really help if you showed how you were creating your JSON feed at cssAttempt3.aspx/ConvertDataTabletoString.

Another problem is that you are using JSON.parse instead of JSON.stringify.

JSON.parse parses a string as JSON.

The opposite, JSON.stringify accepts a value to convert to a JSON string. Your value (response) is already 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!
         }
     });
}

As a side not, a more efficient way to create your JSON is is with an ASHX handler... and will only take minor modifications to your code:

Add [DataContract] and [DataMember] to your class (you need a reference to System.Runtime.Serialization for this to work):

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

And then make the ASHX (Right-click your project -> Add New Item -> 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;
        }
    }
}

then just update your url: url: 'ConvertDataTabletoString.ashx',

这篇关于我不能正确返回这个JSON字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-06 11:54