Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/asp.net/30.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Asp.net 我是否没有正确返回此JSON字符串?_Asp.net_Jquery - Fatal编程技术网

Asp.net 我是否没有正确返回此JSON字符串?

Asp.net 我是否没有正确返回此JSON字符串?,asp.net,jquery,Asp.net,Jquery,我试图使用AJAX从数据库中获取一些值,但每次检查firebug时,我都会看到html副本 function foo() { $.ajax({ type: "POST", url: "cssAttempt3.aspx/ConvertDataTabletoString", data: {}, dataType: 'json',

我试图使用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>
函数foo(){
$.ajax({
类型:“POST”,
url:“cssattent3.aspx/ConvertDataTabletoString”,
数据:{},
数据类型:“json”,
成功:功能(响应){
控制台日志(结果);
//我在这里试过很多东西。
//console.log(响应,响应[0],响应[0]。值,
//JSON.parse(“”)、JSON.parse(response)、JSON.stringify(response)等等。
//每一次,Firebug都会返回html文档。
//在这个html文档中没有什么特别突出的地方。没有错误。
//但有时,萤火虫会说身份不明的人物
//JSON.parse:意外字符
//第4行
//这是不对的,我使用的是谷歌的jQuery,下面的console.log解析正确。
//如果你往上看,结果和反应是两码事
//但是Firebug不会报告任何错误,即使在我编译它的时候。
//我甚至键入了alert(“ASDFSAOF”)来查看发生了什么。什么都没有。
//我也没见过“失败”。
},
失败:函数(){
控制台日志(“失败”);
}
});
};
foo();
log(JSON.parse(“”));
//这与AJAX无关,可以正常工作。
//我从html文档中获取了
我重新编辑了这篇文章,因为我不认为这是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);
            }
        }
    }
}
使用系统;
使用System.Collections.Generic;
使用系统数据;
使用System.Data.SqlClient;
使用System.Runtime.Serialization;
公共部分类cssattent3:System.Web.UI.Page
{
受保护的无效页面加载(对象发送方、事件参数e)
{
}
//此方法用于将datatable转换为json字符串
[System.Web.Services.WebMethod]
公共静态字符串ConvertDataTabletoString()
{
DataTable dt=新的DataTable();
使用(SqlConnection con=newsqlconnection(@“数据源=localhost\SQLEXPRESS;初始目录=personnet;集成安全性=Yes;”)
{
使用(SqlCommand cmd=newsqlcommand(@“从personnet.dbo.accordionTest中选择TOP 200*,con))
{
con.Open();
SqlDataAdapter da=新的SqlDataAdapter(cmd);
da.填充(dt);
System.Web.Script.Serialization.JavaScriptSerializer serializer=新的System.Web.Script.Serialization.JavaScriptSerializer();
列表行=新列表();
字典行;
foreach(数据行dr在dt.行中)
{
行=新字典();
foreach(dt.列中的数据列列列)
{
行添加(列名称,dr[col]);
}
行。添加(行);
}
返回序列化程序。序列化(行);
}
}
}
}

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

因此,尝试以下方法:

    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: 使用

使用Newtonsoft.Json;
List testDictionary=新列表();
字符串json=JsonConvert.SerializeObject(testDictionary);
学分:

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

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

另外,我通常更喜欢在aspx页面
static
上通过Ajax调用方法,因为这表明它们不是“普通”aspx页面的一部分(如果您没有混合功能,并且这个aspx页面的存在只是为了服务Ajax请求,那么它可能没问题)


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

从您的示例和注释来看,您的JSON可能无效。您可以在验证您的输出。如果您展示了您的情况,这将非常有帮助在
cssattent3.aspx/ConvertDataTabletoString
上创建JSON提要

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

将字符串解析为JSON

相反,接受一个值以转换为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
的引用才能工作):

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

公共类ConvertDataTabletoString:IHttpHandler
{     
公共void ProcessRequest(HttpContext上下文)
{
列表m=//填充
MemoryStream stream=新的MemoryStream();
DataContractJsonSerializer s=新的DataContractJsonSerializer(类型(列表));
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!
         }
     });
}
[DataContract]
public class MyDataTableClass
{
    [DataMember]
    private string pro;
    [DataMember]
    private string sn;
    [DataMember]
    private string po;
    //etc
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;
        }
    }
}