DataTable从dataSrc unknown参数中检索json

时间:2017-02-07 06:48:27

标签: html ajax datatables

当我的ajax到datatables的填充结果出现问题时,我已经验证了我的ajax函数是否正常工作并返回结果

Result from the console

这是我的javascript代码:

function getBookingRecords() {
tblDirectLoanReceipt = $('#tbBooking').DataTable();
tblDirectLoanReceipt.destroy();
tblDirectLoanReceipt = $('#tbBooking').DataTable({
    autoWidth: true,
    initComplete: function () {
    },
    processing: true,
    serverSide:true,
    ajax: {
        type: 'post',
        contentType: 'application/json; charset=utf-8',
        url: '/Booking/RetrieveBookingRecords',
        dataSrc: function (json) {
            console.log(json);
            return json;
        },
        columns: [
            { data: 'dsm_description' },
            { data: 'code' }
        ]
    }
});

}

和我的HTML代码:

@section Scripts
{
    @Helper.LoadCustomJS("ViewsJS/Booking/JS_Booking.js", Url)
}

<div class="row">
    <div class="col-md-12">
        <div class="table-responsive">
            <table id="tbBooking">
                <thead>
                    <tr>
                        <th>dsm_description</th>
                        <th>code</th>
                    </tr>
                </thead>
                <tbody></tbody>
            </table>
        </div>
    </div>
</div>

我怎样才能解决这个问题?我错过了什么?感谢您提前提供的任何帮助:)

更新

错误结果

enter image description here

2 个答案:

答案 0 :(得分:0)

您应该尝试确保从ajax返回的json数据格式如下

{
  "data": [
    {
      ...   
      "dsm_description": "Sample description 1",
      "code": "Sample code 1",
      ...
    },
    {
      ...   
      "dsm_description": "Sample description 2",
      "code": "Sample code 2",
      ...
    }]
}   

要格式化返回的json数据,您可以尝试使用库JSON.NET

var listData = new List<Dictionary<string,object>>();  
....
var result = new {Data = listData};
return Content(JsonConvert.SerializeObject(result), "application/json");

答案 1 :(得分:0)

你可以试试这个:

function getBookingRecords() {
  tblDirectLoanReceipt = $('#tbBooking').DataTable();
  tblDirectLoanReceipt.destroy();
  tblDirectLoanReceipt = $('#tbBooking').DataTable({
    autoWidth: true,
    initComplete: function() {},
    processing: true,
    serverSide: true,
    ajax: {
      type: 'post',
      contentType: 'application/json; charset=utf-8',
      url: '/Booking/RetrieveBookingRecords',
      dataSrc: "",
      columns: [{
        data: 'dsm_description'
      }, {
        data: 'code'
      }]
    }
  });

根据我的comment

  

请注意,如果您的Ajax源只是返回一个数据数组   显示而不是对象,将此参数设置为空   字符串。

希望有所帮助。