通过ajax方法向DataTable传递json数据时出错

Error passing json data through ajax method into DataTable

本文关键字:json 数据 出错 传递 DataTable ajax 方法 通过      更新时间:2023-09-26

我得到一个错误在我的IDE在谷歌浏览器的控制台,说明:Uncaught TypeError: Cannot read property 'length' of undefined.dataTables获取原始json数据并试图将其注入到表中时抛出此错误。

 // Got the data - add it to the table
for ( i=0 ; i<aData.length ; i++ ) {
_fnAddData( settings, aData[i] );
}
<script> 
$(document).ready(function(){
    $('#clickMe').click(function(){
    $.ajaxPrefilter(function(options, originalOptions, jqHXR ){
        options.async = true;
    });
$.ajax({
    //type: 'GET',
    url: 'URL',
    dataType:"json",
    data: "getAddressResults", //name of json expression
    success: function(data){
    var jsTable = $('#data').dataTable();
    jsTable.fnClearTable();
    $.each(data, function(key, value){
        var i = this.length;
        alert("There are : " + i + " entries."); //shows how many objects are in my json data 
    jsTable.dataTable().fnAddData([
        value[key].childName,
        value[key].childNum,
        value[key].lineNum,
        value[key].parentName,
        value[key].parentNum
    ]);
});
        if(data){
            var txt = "";
            if(res > 0){
                for (var i=0;i<data.length;i++){
                if (data[i].parentNum && data[i].childNum){
                    txt += "<tr><td>"+data[i].parentNum+"</td><td>"+data[i].childNum+"</td></tr>"
                }
            }
            if(txt !=""){
                $("#data").append(txt).removeClass("hidden");
            }
        }
    }
},
error: function(jqXHR, textStatus, errorThrown){
        alert(textStatus + ': ' + errorThrown);
        }       
    });
        return false;
});

    $('#data').DataTable({
    columns:[
        { title: "childName" },
        { title: "childNum" },
        { title: "lineNum" },
        { title: "parentName" },
        { title: "parentNum" }
        ]
});

去掉<script>标签,你不能在javascript中间放一个html标签