【发布时间】: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中查看网络状态。查看您是否正在通过服务器接收数据。