我有一个Jquery ajax函数,可以调用c#方法。即使它应该返回的字符串是Json格式,该函数也总是返回null。如何在Jquery函数中获取返回值?
function GetScores() {
$.ajax({
type: 'POST',
url: 'Default.aspx/GetTopScores',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (data, textStatus, jqXHR) {
alert(data.d); // Always NULL
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('ERROR!!');
}
});
}
public static string GetTopScores()
{
string result = string.Empty;
DataTable dt = new DataTable();
try
{
using (SqlConnection conn = new SqlConnection())
{
conn.ConnectionString = "Data Source=*****;Initial Catalog=beachlings;Persist Security Info=True;User ID=******;Password=******;MultipleActiveResultSets=True;Application Name=EntityFramework";
conn.Open();
string query = "Select TOP 20 PlayerName, SiteName, Score from HighScores ORDER BY SCORE DESC";
SqlCommand cmd = new SqlCommand(query, conn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
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);
}
string s = JsonConvert.SerializeObject(rows);
return s;
}
}
catch (Exception ex)
{
return null;
}
}
答案 0 :(得分:0)
终于找到导致javascript返回null的原因。我从另一个方法中调用GetTopScores()而不是返回字符串我返回void。谢谢你的帮助:)