我的ajax源代码DataTable无法正确解析吗?

时间:2017-03-15 23:00:34

标签: javascript jquery json ajax datatables

让我们从错误开始......

DataTables warning: tableid=myTable - Requested
unknown parameter 'Name' for row 0, column 0. For more
information about this error, please see http://datatables.net/tn/4

我通过 jsonlint 运行JSON响应以验证其有效性,并检查它以检查数据属性是否存在且非空(所以它不是需要defaultContent)的问题。以下是相关代码:

HTML

<table id="myTable" name="myTable" class="table table-hover">
    <thead>
        <tr>
            <th>Submitter</th>
            <th>Submit Date</th>
            <th>Is Restricted</th>
            <th>Libraries</th>
            <th>RequestID</th>
        </tr>
    </thead>
</table>

JS

var table = $("#myTable").DataTable({
    ajax: {
        url: "MyPage.aspx/GetRequests",
        dataSrc: "d",
        type: "POST",
        contentType: "application/json; charset=utf-8"
    },
    columns: [
        { data: "Name", name: "submitter" },
        { data: "SubmitDate", name: "submit-date" },
        { data: "IsRestricted", name: "is-restricted" },
        { data: "Libraries", name: "libraries" },
        { data: "RequestID", name: "request-ID" }
    ],
    info: false,
    paging: false,
    searching: false,
    select: "single"
});

dataSrc: "d"是要在响应中读取的属性:

as a nested property d of the response

以下是JSON响应的片段:

{"d":"[{
    \"RequestID\":50,
    \"Status\":0,
    \"Libraries\":
        [{\"l_id\":0,
        \"library_name\":\"Cat Books\",
        \"request_id\":50,
        \"action\":0,
        \"action_by\":null,
        \"granted_by\":null,
        \"action_date\":\"\\/Date(1488475446477)\\/\"},
        {\"l_id\":0,
        \"library_name\":\"Dog Books\",
        \"request_id\":50,
        \"action\":0,
        \"action_by\":null,
        \"granted_by\":null,
        \"action_date\":\"\\/Date(1488475446477)\\/\",
        }],
    \"Name\":\"Alshon Jeffrey\",
    \"Department\":null,
    \"SubmitDate\":\"\\/Date(1488475446477)\\/\",
    \"IsRestricted\":true}]"}

该表(在错误警报两次之后),如下所示:

all null cells

我已尝试清空Libraries属性,以确保DataTables不会尝试将该集合解析为表,同样的错误。响应中的d是否仍在关闭DataTables?或表结构不对?我尝试添加tbody占位符但没有运气,并再次使用tbody > tr > td占位符。在这一点上,我几乎没有想法......

如果重要,可以使用asp.net webforms,[WebMethod]使用JavaScriptSerializer

修改

这是我用来生成JSON的服务器端代码。我已经尝试了JavaScriptSeralizerJsonConvert,我认为两种方法都生成相同的JSON,并且两者的响应中的JSON都在d中:

[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static string GetRequests()
{
    var requests = DataGetter.GetRequests().OrderBy(r => r.SubmitDate).ToList();

    return new JavaScriptSerializer().Serialize(requests);

    // Have also tried:
    // return JsonConvert.SerializeObject(requests);
}

1 个答案:

答案 0 :(得分:1)

我的第一个建议是,转储JavaScriptSerializer,转而使用NewtonSoft序列化程序。如果您使用的是visual studio 15,它可能已经免费提供了更好的工作。

以下是我的Web方法从我的数据结构开始的样子:

  public class wsService : System.Web.Services.WebService
{

    public struct dtData
    {
        public string name;
        public string position;
        public Int32 salary;
        public string start_date;
        public string office;
        public string extn;
    }

    [WebMethod]
    public string GetDTDataSerializedList(string parameters)
    {
        return JsonConvert.SerializeObject(getDataTableData());
    }

    private List<dtData> getDataTableData()
    {
        List<dtData> dataList = new List<dtData>();
        dtData item = new dtData();

        item.name = "Tiger Nixon";
        item.position = "System Architect";
        item.salary = 320800;
        item.start_date = "2011/04/25";
        item.office = "Edinburgh";
        item.extn = "5421";
        dataList.Add(item);
      //blah blah blah more objects added then return
      // I hard coded the data just for testing and dev
        return dataList;
    }
}

以上可能与您的相似。 我不使用dataSrc。相反,我使用dataFilter部分将数据放入DataTables期望的表单中。 以下是数据表的相关部分:

                var table = $('#example').DataTable({
                    'processing': false,
                    // Again, this code will not work if serverSide is set to true.
                    'serverSide': false,
                    'ajax': {
                        // I used an asmx page in my own development environment to get the data.
                        url: 'wsService.asmx/GetDTDataSerializedList',
                        type: "post",
                        data: function(dtparms){
                            return JSON.stringify({ parameters: JSON.stringify(dtparms) });
                        },
                        contentType: "application/json; charset=utf-8",

                       // dtData is what has been returned in the server
                        dataFilter: function (dtData) {
                            // I parse it so I can get to the data in "d"
                            var p = JSON.parse(dtData);
                            // the data inside the d is also serialized 
                            // so I have to parse it out a second time
                            var d = JSON.parse(p.d);j

                            // then reserialize and return it in a form
                            // that datatables likes.
                            return JSON.stringify({ data: d });
                        },
                    },