【发布时间】:2021-08-20 01:58:32
【问题描述】:
我只是想使用 ajax 调用附加到我的 html tbody 标记。 我的代码看起来像这样。这些数据只是我连接到我的数据库的演示数据。
C#
public static string GetEmployee()
{
List<Employee> lstEmployee = new List<Employee>();
string cs = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
using (SqlConnection con = new SqlConnection(cs))
{
SqlCommand cmd = new SqlCommand("spGetEmployee", con);
cmd.CommandType = CommandType.StoredProcedure;
con.Open();
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
Employee emp = new Employee();
emp.Id = Convert.ToInt32(rdr["EmployeeId"]);
emp.FirstName = rdr["FirstName"].ToString();
emp.LastName = rdr["LastName"].ToString();
emp.Email = rdr["Email"].ToString();
lstEmployee.Add(emp);
}
}
var json = JsonConvert.SerializeObject(lstEmployee);
return json;
}
HTML
<table id="employees" style="border-collapse: collapse" border="1">
<thead>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Email</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
我的 Json 对象
[
{"Id":1,"FirstName":"John","LastName":"abc","Email":""},
{"Id":2,"FirstName":"John","LastName":"abc","Email":""},
{"Id":3,"FirstName":"Phillip","LastName":"abc","Email":""},
{"Id":4,"FirstName":"Ken","LastName":"abc","Email":""},
{"Id":5,"FirstName":"Miranda","LastName":"abc","Email":""},
{"Id":6,"FirstName":"Liv","LastName":"abc","Email":""}
]
我的 Ajax 调用是问题所在。不知何故,我无法弄清楚如何遍历响应数据。 我得到了什么
- 名字姓氏电子邮件
未定义未定义未定义
只有一行未定义。不确定我做错了什么,因为我在控制台日志中没有看到任何错误。
function loadEmployees() {
var tboby = $('#employees tbody');
tboby.empty(); //clear the data
//ajax call to cs file
$.ajax({
url: "jqueryDialogSaveToDB.aspx/GetEmployee",
type: "post",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
$(data).each(function () {
var tr = $('<tr></tr>')
tr.append('<td>' + this.FirstName + '</td>')
tr.append('<td>' + this.LastName + '</td>')
tr.append('<td>' + this.Email + '</td>')
tboby.append(tr);
});
},
failure: function (response) {
alert("data failure" + response.data);
}
});
}
更新 当我控制台记录它时,这是我来自后端的响应 Json 对象。 当我尝试
JSON.parse(data); // this is json object coming in from backend
我收到错误消息,因为它认为响应对象未定义。 感谢您的观看。
【问题讨论】:
-
不应该真正将数组包装在
$()中。试试$.each(data, function(i, obj){ .... obj.FirstName.... }) -
还要检查实际响应以确保由于某种原因数组中没有空对象