Datatables.net error on Ajax load

2019-08-19 01:30发布

I am working on a simple ajax example in datatables and it is not working and I am at a loss to explain it. I have a simple table as follows:

<table id="tblAddresses">
  <thead>
    <tr>
        <th>Street Address</th>
        <th>City</th>
        <th>State</th>
        <th>Zip Code</th>
    </tr>
 </thead>
 <tfoot>
    <tr>
        <th>Street Address</th>
        <th>City</th>
        <th>State</th>
        <th>Zip Code</th>
        </tr>
 </tfoot>
</table>

I have a json data source with data that looks like this (I prettied it up a bit for display here but the file is one long line with no line breaks).

{"data":[{"street":"19 Brook Avenue","city":"PASSAIC","state":"NJ","postcode":"07055"},
{"street":"27 Brook Avenue","city":"PASSAIC","state":"NJ","postcode":"07055"},
{"street":"31 Brook Avenue","city":"PASSAIC","state":"NJ","postcode":"07055"},
{"street":"35 Brook Avenue","city":"PASSAIC","state":"NJ","postcode":"07055"},
{"street":"39 Brook Avenue","city":"PASSAIC","state":"NJ","postcode":"07055"},
{"street":"49 Brook Avenue","city":"PASSAIC","state":"NJ","postcode":"07055"}]}

Finally, I load it in my document ready function:

<script type="text/javascript">
    $(document).ready(function(){
        $("#tblAddresses").DataTable({
            "ajax" : {
                "url" : "/json/07055.json",
                "columns" : [{"data":"street"},
                             {"data":"city"},
                             {"data":"state"},
                             {"data":"postcode"}]
            }
        });
    });
</script>

When I load the page, I see the ajax call. I can see the data accepted by the browser but DataTables is giving me an error:

DataTables warning: table id=tblAddresses - Requested unknown parameter '0' for row 0, column 0.

I have worked with ajax many times before albeit never loading from a static data file. I can't find the error in the JSON or Javascript.

1条回答
孤傲高冷的网名
2楼-- · 2019-08-19 02:14

You are binding data in wrong way. You need to bind columns after ajax method, like bellow,

$("#tblAddresses").DataTable({
        "ajax" : {
            "url" : "/json/07055.json",
            "type": "Get"
        }, //Here end of ajax method. Now you can bind the columns
         "columns" : [{"data":"street"},
                      {"data":"city"},
                      {"data":"state"},
                      {"data":"postcode"}]
        });

Hope it helps!

查看更多
登录 后发表回答