如何更改ASP.NET中的DataTables处理的ajax响应?

时间:2016-11-11 08:28:18

标签: jquery asp.net ajax webforms datatables

您可能知道,ASP.NET使用d参数提供ajax响应。我试图改变这个:

dataSrc: function (json) {
    return json.d.data;
}

但是当我运行它时,它会显示jquery.dataTables.js:4108 Uncaught TypeError: Cannot read property 'length' of undefined(…).正如您在此帖子中附带的图片上看到的那样。我检查了那部分,我得出结论dataSrc并没有真正改变所有的反应。

enter image description here

这就是我为DataTables的ajax选项所做的:

dataTable: {
    ajax: {
        type: 'POST',
        url: window.location.href + '/GetData',
        contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        dataSrc: function (json) {
            return json.d.data;
        },
        ..... //other options
}

那么,还有其他选项可以改变DataTables将处理的所有响应吗?

2 个答案:

答案 0 :(得分:1)

您可以在 dataSrc 中尝试此操作。此解决方案基于此link

"dataSrc": function (data) {
    var json = $.parseJSON(data.d);

    var myData = {};
    myData.draw = parseInt(json.draw);
    myData.recordsTotal = parseInt(json.recordsTotal);
    myData.recordsFiltered = parseInt(json.recordsFiltered);
    myData.data = json.data;

    return myData.data;
 }

答案 1 :(得分:0)

问题是你没有解析响应。首先将ajax调用分开并在解析为aaData(数据表道具)后分配该响应。

并确保您必须指定要在表格中显示的所有列,请参阅代码中的"aoColumns": [{ "mData": "YourColumnName1" }]。希望这会对你有所帮助

 var ResponseData = CallAjaxMethod(YourUrl, "");//This will make Ajax call and get response
    ResponseData = JSON.parse(ResponseData); //This will pars your response

//'#tblId' this is table id where you want to show your table
$('#tblId').DataTable({
        "bProcessing": true,
        "bDestroy": true,
        "bStateSave": true,
        "aaData": ResponseData,//Its your response 
        "aoColumns": [
            { "mData": "YourColumnName1" },
            ....
            { "mData": "YourColumnNamen },

        ]
    });