DataTables Jquery Ajax对象找不到数组列

我正在尝试使用带有 Ajax 数据源的 jquery.dataTables 将 json 数据拉入 html 表中。


我面临一个问题,它无法在 JSON 响应中找到我正在寻找的数据,我正在努力寻找我的问题所在。我收到一个未定义的错误,因为它无法匹配我请求的数据列。


在 Snipped-I 中删除了 URL,但这里是返回的对象结构的示例。


{

    "success": true,

    "result": [

        {

            "type": "gift",

            "name": "Gift",

            "rewards": [

                {

                    "name": "Item Name",

                    "image_url": "https://xxx.jpg",

                    "minimum_display_price": "500+ bucks",

                    "description": {

                        "text": "text here",

                        "html": "html here"

                    },

                    "disclaimer_html": "disclaimer",

                    "warning": null,

                    "denominations": [

                        {

                            "id": "5ca1737f1sdasdsadsad2cb5f004cc0d564",

                            "name": "Name",

                            "price": 500,

                            "display_price": "500",

                            "available": true

                        }

                    ]

                }

            ]

        }

    ]

}

$(document).ready(function() {

    $('#example').DataTable( {

        "ajax": "myurlishere",

        "columns": [ 

            { "result[0]": "name" }

            //{ "result": "rewards.name"}

            // {"data": "name"}

            

        ]

    } );


慕妹3242003
浏览 169回答 2
2回答

鸿蒙传说

看起来您有一些嵌套的数据对象,虽然可以直接在 DataTable 中处理这个问题,但在将数据交给 DataTable 进行渲染之前预处理数据可能更容易。这会将您的嵌套数据转换为奖励对象的平面数组,这将使渲染变得更容易。(async function() {    const rawData = await fetch("your_url").then(data => data.json());    const finalData = rawData.result.map(category => category.rewards).flat(1);    $("#example").DataTable({        data: finalData,        columns: [{ data: "name" }]    });})();

江户川乱折腾

可能是您需要更改代码,只需检查以下方式,$(document).ready(function() {$('#example').DataTable( {    "ajax": "myurlishere",    "columns": [        { "data": "name" },        { "data": "rewards[, ].name" },        { "data": "rewards[, ].image_url" },        { "data": "rewards[, ].description.text" },        { "data": "rewards[, ].denominations[,].name" },    ]} );} );
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript