我想使用jQuery数据表显示数据。我正在使用Webmethod从C#传递JSON响应。 jQuery正在接收的数据格式正确。数据表显示某些行的空结构和警报,如下所示:
数据表警告:表id - 示例请求第0行的未知参数1.
此外,表格结构显示第1列中的双引号,就是这样。
我搜索了那个警报,但获得的信息根本没用。我错过了一些东西。请帮我这个。
我的代码:
$(document).ready(function () {
$.ajax({
type: "POST",
url: "data_table2.aspx/BindDatatable",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
console.log(JSON.parse(data.d));
console.log(JSON.parse(data.d));
$('#example').dataTable({
"aaData": data.d,
"aoColumns": [
{ "aaData": "UserId" },
{ "aaData": "UserName" },
{ "aaData": "Location" }
]
});
}
});
});
WEBMETHOD:
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static string BindDatatable()
{
DataTable dt = new DataTable();
dt = getData();
List<User5> data = new List<User5>();
foreach (DataRow dtrow in dt.Rows)
{
User5 user = new User5();
user.UserId = dtrow["id"].ToString();
user.UserName = dtrow["name"].ToString();
user.Location = dtrow["city"].ToString();
data.Add(user);
}
System.Web.Script.Serialization.JavaScriptSerializer jSearializer = new System.Web.Script.Serialization.JavaScriptSerializer();
string aaData = jSearializer.Serialize(data);
// aaData = "{\"data\": " + aaData + "}";
return aaData;
}
jQuery收到的数据是:
[{
"UserId": "2",
"UserName": "Nitin",
"Location": "Mumbai"
}, {
"UserId": "3",
"UserName": "NAkshay",
"Location": "Thane"
}, {
"UserId": "4",
"UserName": "Nil",
"Location": "Pune"
}, {
"UserId": "5",
"UserName": "Vinit",
"Location": "KArve nagar"
}, {
"UserId": "6",
"UserName": "Rahul",
"Location": "Kothrud"
}, {
"UserId": "7",
"UserName": "Pravin",
"Location": "Hinjewadi"
}, {
"UserId": "8",
"UserName": "Pavan",
"Location": "Mg City"
}]
如果我在c#代码中删除了该注释行,则o / p将为
{
"data": [{
"UserId": "2",
"UserName": "Nitin",
"Location": "Mumbai"
}, {
"UserId": "3",
"UserName": "NAkshay",
"Location": "Thane"
}, {
"UserId": "4",
"UserName": "Nil",
"Location": "Pune"
}, {
"UserId": "5",
"UserName": "Vinit",
"Location": "KArve nagar"
}, {
"UserId": "6",
"UserName": "Rahul",
"Location": "Kothrud"
}, {
"UserId": "7",
"UserName": "Pravin",
"Location": "Hinjewadi"
}, {
"UserId": "8",
"UserName": "Pavan",
"Location": "Mg City"
}]
}
答案 0 :(得分:1)
$('#example').dataTable({
"aaData": JSON.parse(data.d),
"aoColumns": [
{ "mData": "UserId" },
{ "mData": "UserName" },
{ "mData": "Location" }
]
});
需要使用&#34; aaData&#34;: JSON.parse(data.d)解析信息。