如何将Ajax成功函数响应作为数据表的输入

时间:2019-02-18 04:37:39

标签: json ajax

我编写了一个脚本代码,该脚本代码通过发送一个值来调用getdata.php,我得到的json格式的成功函数响应如下所示。

我的脚本代码:

<script>
 function getId(val) {
 alert(val);
    $.ajax({
     type: "post",
    url: "getdata.php",
    data: 'id=' + val,
    dataType: "JSON",                  
    success: function(response){ 
      console.log(response);
    }                       
            /*$('#city').dataTable({
             "bProcessing": true,
             "sAjaxSource": "JSON.parse(this.response)",
             "aoColumns": [
                    { mData: 'id' } ,
                    { mData: 'vid' },
                    { mData: 'date' },
                    { mData: 'latitude' },
                    { mData: 'longitude' },
                    { mData: 'speed' },
                    { mData: 'batery' },
                    { mData: 'totalkm' },
                    { mData: 'intrkm' },
                    { mData: 'control' }

            ]
    }); */


 });
}
</script>

和我的响应json数据:

{"sEcho":1,"iTotalRecords":2,"iTotalDisplayRecords":2,"aaData":[{"id":"1","vid":"A0001","date":"2019-02-07 15:58:53","latitude":"17.00","longitude":"82.20","speed":"25","batery":"98","totalkm":"8","intrkm":"8","control":"0"},{"id":"2","vid":"A0001","date":"2019-02-07 15:58:53","latitude":"17.10","longitude":"82.30","speed":"26","batery":"97","totalkm":"15","intrkm":"15","control":"0"}]}

console.log(response);就像

{sEcho: 1, iTotalRecords: 2, iTotalDisplayRecords: 2, aaData: Array(2)}
aaData: Array(2)
0: {id: "1", vid: "A0001", date: "2019-02-07 15:58:53", latitude: "17.00", 
longitude: "82.20", …}
1: {id: "2", vid: "A0001", date: "2019-02-07 15:58:53", latitude: "17.10", 
longitude: "82.30", …}
length: 2
__proto__: Array(0)
iTotalDisplayRecords: 2
iTotalRecords: 2
sEcho: 1

现在,如何将ajax调用的响应给予数据表sAjax源,并读取列数据并将其呈现在#city中。 请帮助我,我在这里被感动。

1 个答案:

答案 0 :(得分:0)

DataTables能够从Ajax可以获取的几乎任何JSON数据源读取数据。可以通过将ajax选项设置为JSON数据源的地址,以最简单的形式完成此操作。

$(document).ready(function() {
    $('#city').DataTable( {
        "ajax": 'getdata.php?any_value=1'
    });
});

请参阅更多详细信息:https://datatables.net/examples/data_sources/ajax