gpt4 book ai didi

asp.net - 我没有正确返回这个 JSON 字符串吗?

转载 作者:行者123 更新时间:2023-12-01 04:12:08 25 4
gpt4 key购买 nike

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

最佳答案

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

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

JSON.parse字符串解析为 JSON。

相反,JSON.stringify接受要转换为 JSON 字符串的值。您的值(响应)已经是 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',

关于asp.net - 我没有正确返回这个 JSON 字符串吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19116385/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com