显示错误显示d未定义。 全文是:JavaScript运行时错误:无法获取属性' length'未定义或空引用。 我无法理解为什么它没有显示数据。在数据库中它有两个记录。
这里是HTMl,一个按钮
HTML
<h3>Load Data</h3>
<input id="btnLoadData" type="button" value="Load Database" onclick="GetCompanies()" />
<div id="UpdatePanel">
</div>
这里是ajax调用
使用jQuery调用Ajax
function GetCompanies() {
$("#UpdatePanel").html("<div style='text-align:center'>Please Wait</div>")
$.ajax({
type: "POST",
url: "WebForm1.aspx/GetCompanies",
data: "{}",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: onSuccess,
error: onError
});
}
function onSuccess(data) {
var tableContent = "<table border='0'>" +
"<tr>" +
"<td>Rank</td>" +
"<td>Company Name</td>" +
"<td>Revenue</td>" +
"<td>Industry</td>" +
"</tr>";
for (var i = 0; i < data.d.length; i++) { //d is undefined
tableContent+=
"<tr>" +
"<td>"+data.d[i].Rank+"</td>" +
"<td>"+data.d[i].CompanyName+"</td>" +
"<td>"+data.d[i].Revenue+"</td>" +
"<td>" + data.d[i].Industry + "</td>" +
"</tr>";
}
tableContent += "</table>";
$("#UpdatePanel").html(tableContent);
}
function onError(data) {
}
后端代码
[WebMethod]
[ScriptMethod(ResponseFormat=ResponseFormat.Json)]
public static List<TopCompany> GetCompanies()
{
List<TopCompany> allCompany = new List<TopCompany>();
using (MyDatabaseEntities db = new MyDatabaseEntities())
{
allCompany = db.TopCompanies.ToList();
}
return allCompany;
}
需要帮助来找出错误。
答案 0 :(得分:1)
通过评论以下声明来解决
// settings.AutoRedirectMode = RedirectMode.Permanent;
在App_Start / RouteConfig.cs
中答案 1 :(得分:0)
function GetCompanies() {
$("#UpdatePanel").html("<div style='text-align:center'>Please Wait</div>")
$.ajax({
type: "POST",
url: "WebForm1.aspx/GetCompanies",
data: "{}",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: onSuccess,
error: onError
});
}
function onSuccess(data) {
var tableContent = "<table border='0'>" +
"<tr>" +
"<td>Rank</td>" +
"<td>Company Name</td>" +
"<td>Revenue</td>" +
"<td>Industry</td>" +
"</tr>";
for (var i = 0; i < data.length; i++) { //d is undefined
tableContent+=
"<tr>" +
"<td>"+data[i].Rank+"</td>" +
"<td>"+data[i].CompanyName+"</td>" +
"<td>"+data[i].Revenue+"</td>" +
"<td>" + data[i].Industry + "</td>" +
"</tr>";
}
tableContent += "</table>";
$("#UpdatePanel").html(tableContent);
}
function onError(data) {
}