我需要创建一个数据表(jquery)绑定到ajax(C#WebMethod)
1-WebMethod返回json
numberOfSections
2-客户端脚本
public string GetProjects()
{
DataTable dt = new DataTable("ProjectData");
string Conn = System.Configuration.ConfigurationManager.ConnectionStrings["GPS_TrackingConnectionString"].ConnectionString;
SqlConnection conn = new SqlConnection(Conn);
conn.Open();
SqlCommand comm = new SqlCommand("SP_GetAll_Projects", conn); // / + branch, conn);
comm.CommandType = CommandType.StoredProcedure;
dt.Load(comm.ExecuteReader());
conn.Close();
DataSet ds = new DataSet();
ds.Tables.Add(dt);
JavaScriptSerializer js = new JavaScriptSerializer();
//return ds.GetXml();
//Context.Response.Write(js.Serialize(dt));
var list = JsonConvert.SerializeObject(dt,
Formatting.None,
new JsonSerializerSettings()
{
ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
});
return list;
// return (js.Serialize(dt));
}
}
3- HTML
$(document).ready(function () {
$("#myTable").dataTable({
"bJQueryUI": true,
"sPaginationType": "full_numbers",
"bServerSide": true,
"sAjaxSource": "Query.asmx/GetCars",
"fnServerData": function (sSource, aoData, fnCallback) {
$.ajax({
"type": "POST",
"dataType": 'json',
"contentType": "application/json; charset=utf-8",
"url": sSource,
// "data": "{'sEcho': '" + aoData[0].value + "'}",
"success": function (msg) {
alert(msg.d);
fnCallback(msg.d);
}
});
},
"columns": [
{ "data": "Name" }
]
});
});
4- json结果
此XML文件似乎没有与之关联的任何样式信息。文档树如下所示。 [{" ID":1,"名称":" MH""起始日期":空,"结束日期"日期null},{" ID":2"名称":" RF""起始日期":空,"结束日期& #34;:空}] 4-目前的情况 成功中的警报显示正确的数据 但该表未显示数据我的问题是如何告诉数据表表列名称转到数据列名称 没有控制台错误
谢谢
答案 0 :(得分:0)
试试这个
var Table1 = $('#myTable').DataTable({
ajax: {
url: "Query.asmx/GetCars",
type: "POST",
"datatype": "json",
dataSrc: ""
},
"columns": [
{ "data": "Name", "name": "Name" }
],
"bDestroy": true,
"serverSide": true,
"pageLength": 25,
"processing": true,
"searching": false,
"bSort": false,
});
<table id="myTable" width="100%">
<thead>
<tr>
<th>Name</th>
</tr>
</thead>
<tbody></tbody></table>
答案 1 :(得分:0)
如果你的json回复是[{"id":1,"Name":"mh","StartDate":null,"EndDate":null},{"id":2,"Name":"rf","StartDate":null,"EndDate":null}]
将您的代码更改为
$(document).ready(function () {
$("#myTable").dataTable({
"bJQueryUI": true,
"sPaginationType": "full_numbers",
"bServerSide": true,
"sAjaxSource": "Query.asmx/GetCars",
"fnServerData": function (sSource, aoData, fnCallback) {
$.ajax({
"type": "POST",
"dataType": 'json',
"contentType": "application/json; charset=utf-8",
"url": sSource,
// "data": "{'sEcho': '" + aoData[0].value + "'}",
"success": function (msg) {
alert(msg.d);
fnCallback(msg.d);
}
});
},
"columns": [
{ data: 'id' },
{ data: 'Name' },
{ data: 'StartDate' },
{ data: 'EndDate' }]
});
});