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