jQuery数据表没有填充

时间:2018-01-05 19:35:21

标签: jquery asp.net datatables

我有一个jQuery数据表,通过Web服务API获取数据。我可以看到返回的数据格式正确,但表格没有显示数据。

我有一个“提交”按钮,点击后可以获取数据并重绘表格。我在“成功”函数中放置了一个断点,可以看到json数据。

在aspx页面和数据表定义之上的Javascript(我需要这个js函数,因为数据表顶部的搜索文本框在页面重新加载时不断消失)

<script>
    $(function () {
        bindDataTable(); // bind data table on first page load
        // bind data table on every UpdatePanel refresh
        Sys.WebForms.PageRequestManager.getInstance().add_endRequest(bindDataTable);
    });

    function bindDataTable() {
        var FacCertDT = $('#tblFacCert').DataTable({
            'bDestroy': true,
            "bStateSave": true,
            dom: 'lfrtip',
            "fnStateSave": function (oSettings, oData) {
                localStorage.setItem('tblFacCert', JSON.stringify(oData));
            },
            "fnStateLoad": function (oSettings) {
                return JSON.parse(localStorage.getItem('tblFacCert'));
            }
        });
    }
</script>

<div runat="server" id="divFacCert" ClientIDMode="Static" style="padding:15px">
    <div class="table-responsive">
        <table id="tblFacCert" class="table table-striped table-bordered table-hover">
            <thead>
                <tr class="info">
                    <th>Area</th>
                    <th>District</th>
                    <th>MPOO </th>
                    <th>Facility</th>
                    <th>Type</th>
                    <th>Sub-Type</th>
                    <th>Response Due Date</th>
                    <th>Completed?</th>
                    <th>Completed By</th>
                    <th>Completed On</th>
                </tr>
            </thead>
        </table>
    </div>
</div>

页面底部的Javascript:

<script>
    Table = $("#tblFacCert").DataTable({
        data: [],
        "aoColumns": [
            {
                "mData": "Area"
            }, {
                "mData": "District"
            }, {
                "mData": "MPOO"
            }, {
                "mData": "FacilityName"
            }, {
                "mData": "FacilityType"
            }, {
                "mData": "FacilitySubType"
            }, {
                "mData": "ResponseDueDate"
            }, {
                "mData": "Completed"
            }, {
                "mData": "UserName"
            }, {
                "mData": "ResponseDate"
            }
        ],
        "pageLength": 15,
        "deferRender": true,
        rowCallback: function (row, data) { },
        filter: false,
        info: false,
        ordering: false,
        processing: true,
        retrieve: true
    });

    $("#btnSubmit").on("click", function (event) {
        $.ajax({
            type: "POST",
            dataType: "json",
            contentType: "application/json; charset=utf-8",
            url: "../services/easg.asmx/GetComplianceReportData",
            cache: false,
            contentType: "application/json; charset=utf-8",
            data: "{ 'startDate': '" + $("#tbStartDate").val() + "', 'certID': '" + $('#ddlCertificate').val() + "'}"
        }).done(function (result) {debugger
            Table.clear().draw();
            Table.rows.add(result).draw();
            }).fail(function (jqXHR, textStatus, errorThrown) {
                alert(textStatus + ' - ' + errorThrown);
        });
    })
</script>

这就是Web服务API的样子:

namespace FacCert
{
    /// <summary>
    /// Summary description for easg
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]

    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
    [System.Web.Script.Services.ScriptService]
    public class easg : System.Web.Services.WebService
    {

        [WebMethod]
        [ScriptMethod(UseHttpGet = false, ResponseFormat = ResponseFormat.Json)]

        public string GetComplianceReportData(string startDate, string certID)
        {
            DateTime dtStartDate = Convert.ToDateTime(startDate);
            int iCertItemID = int.Parse(certID);
            DataTable dt = FacCompliance.GetFacCompliances(dtStartDate, iCertItemID);
            string JSONresult;
            JSONresult = JsonConvert.SerializeObject(dt);
            return JSONresult;
        }
    }
}

当我在“on(”click“)”中检查它时,这是数据:

[
    {
        "Area":"CAPITAL METRO (K)",
        "District":"NORTHERN VIRGINIA",
        "MPOO":"Plant",
        "FacilityName":"DULLES VA P&DC",
        "FacilityType":"Network Operations",
        "FacilitySubType":"P&DC",
        "ResponseDueDate":"2017-12-20T00:00:00",
        "ResponseDate":"2017-12-30T17:57:35.353",
        "UserACEID":"XXXXXX",
        "UserName":"John Doe",
        "Completed":"Yes",
        "AreaID":11,
        "DistrictID":58,
        "FacID":2261,
        "FacComplianceID":1
    },{
        "Area":"CAPITAL METRO (K)",
        "District":"NORTHERN VIRGINIA",
        "MPOO":"Plant",
        "FacilityName":"NORTHERN VA P&DC",
        "FacilityType":"Network Operations",
        "FacilitySubType":"P&DC",
        "ResponseDueDate":"2017-12-20T00:00:00",
        "ResponseDate":"2017-12-30T18:23:10.86",
        "UserACEID":"XXXXXX",
        "UserName":"John Doe",
        "Completed":"Yes",
        "AreaID":11,
        "DistrictID":58,
        "FacID":2262,
        "FacComplianceID":4
    }
]

我已经搜索并尝试了所有建议,但似乎没有解决问题。我希望有人在这里可以看到我搞砸了。

API返回了一些我没有包含在数据表中的列(例如,AreaID,DistrictID,...)。

更新

如果我替换Table.rows.add(result).draw()中的变量“result”;使用我在帖子中列出的实际json数组,然后显示数据。我通过放置一个断点并检查“结果”的值得到了json数据,所以我不确定为什么它在我使用实际的json数据时工作,而不是当我传递“结果”时。

2 个答案:

答案 0 :(得分:1)

在Ajax done方法中替换此行:

Table.rows.add(JSON.parse(result.d)).draw();

修改 如果您使用的是更新面板,则可以将js方法与您的更改反映出来。在functuon中输入您的按钮提交代码并将您的方法名称设置为参数。我希望它的工作

<script type="text/javascript">
  Sys.WebForms.PageRequestManager.getInstance().add_endRequest(YourMethod);
    </script>

答案 1 :(得分:0)

花了很多时间在这上面我发现了问题所在。当我将实际的json数据传递给Table.rows.add()时,显示了数据。所以我知道我传递的“结果”参数有问题。当我查看Chrome中返回的响应时,我注意到它正在添加XML标记:

<string xmlns="http://tempuri.org/">
[
    {
        "Area":"CAPITAL METRO (K)",
        "District":"NORTHERN VIRGINIA",
        ....
    }
]
</string>

这就是原始数据显示的原因,但是当我向其传递“result”参数时却没有。

修复方法是更改​​按钮单击功能,如下所示:

$("#btnSubmit").on("click", function (event) {
    $.ajax({
        type: "POST",
        dataType: "json",
        contentType: "application/json; charset=utf-8",
        url: "../services/easg.asmx/GetComplianceReportData",
        cache: false,
        data: "{ 'startDate': '" + $("#tbStartDate").val() + "', 'certID': '" + $('#ddlCertificate').val() + "'}"
    }).done(function (result) {
        Table.clear().draw();
        jResult = JSON.parse(result.d); <--- This is the fix
        Table.rows.add(jResult).draw();
    }).fail(function (jqXHR, textStatus, errorThrown) {
        alert(textStatus + ' - ' + errorThrown);
    });
})