为何DataTable无法加载Ajax请求返回的JSON数据?
问题:Ajax获取数据后无法填充DataTable
之前成功通过Ajax调用加载DataTable,但现在浏览器调试工具确认API已返回正确JSON数据,却无法将数据填充到表格中,求技术帮助。
JavaScript代码
$(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"); }); });
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" }
问题原因与解决方法
DataTable的data参数要求传入数组格式的数据源,但当前API返回的是单个对象,无法被表格识别为行数据。
修改Ajax成功回调中的代码,将单个对象包装成数组即可:
success: function (json) { console.log("success"); $('#myTable').DataTable({ data: [json], // 将单个对象放入数组 columns: [ { data: 'first_name' }, { data: 'last_name' } ] }); },
另外,之前声明的let data;变量可以直接移除,无需额外存储,直接使用回调参数json即可。
内容的提问来源于stack exchange,提问作者Justin Zitel
相关产品推荐
相关产品推荐

