jquery 为什么我的DataTable没有填入数据?

9udxz4iz  于 2023-05-17  发布在  jQuery
关注(0)|答案(1)|浏览(123)

我正在尝试从 AJAX 调用加载数据表。我以前成功地做到了这一点,看看我以前是如何做到的,我不确定什么是正确的。
JavaScript:

<script>$(document).ready(function () {
    let data;
    $.ajax({
        url: "https://pure-peak-65624.herokuapp.com/https://api.sportradar.us/golf/trial/v3/en/players/da226913-b804-48de-adbf-96e956eb75ac/profile.json?api_key=rupvugmcybede53f3svuqqa8",
        dataType: 'json',
        success: function (json) {
            console.log("success");
            data = json;
            $('#myTable').DataTable({
                data: data,
                columns: [                            
                    { data: 'first_name' },
                    { data: 'last_name' }
                ]
            });
        },
        error: function (e) {
            console.log("error");
        }
    });

    $("#myTable").on('click', 'tr', function () {
    alert($(this).text() + " was clicked");
    console.log("working");
});
});
</script>

HTML:

<body>
<div class="banner">
    <div class="navbar">
        <img src="images/logo.svg" class="logo">
        <ul>
            <li><a href="home.html">Home</a></li>
            <li><a href="about.html">About</a></li>
            <li><a href="benefits.html">Benefits</a></li>
            <li><a href="photos.html">Photos</a></li>
            <li><a href="stats.html">Stats</a></li>
        </ul>
    </div>
</div>
<div class="content">
    <h1>Welcome to Statsland</h1>
    <div id="leaderboard">
        <table id="myTable" class="display compact nowrap">
            <thead>
                <tr>
                    <th>First Name</th>
                    <th>Last Name</th>
                </tr>
            </thead>
        </table>
    </div>
</div>

API调用返回的JSON示例:

{
"id": "da226913-b804-48de-adbf-96e956eb75ac",
"first_name": "Rory",
"last_name": "McIlroy",
"height": 70,
"weight": 160,
"birthday": "1989-05-04",
"country": "NORTHERN IRELAND",
"residence": "Holywood,, IRL",
"birth_place": "Holywood,, IRL",
"turned_pro": 2007,
"handedness": "R",
"abbr_name": "R.McIlroy",
"name": "McIlroy, Rory"
}

使用浏览器检查工具,我可以看到API调用返回了正确的json,但我不知道如何将其放入DataTable。任何帮助都很感激。

mwngjboj

mwngjboj1#

首先检查你 AJAX 链接的响应(通常在请求头中有错误)。
然后:

var columns = [];

...
...

success: function (json) {
        console.log("success");
        data = JSON.parse(data);
        columns.push(
                { data: 'first_name' },
                { data: 'last_name' }
        )
        $('#myTable').DataTable({
            data: data.data,
            columns: columns

        });
    },

相关问题