简体   繁体   中英

Empty table body in jQuery DataTables

I'm a newbie to jQuery, so, please, don't judge me for my dumb question. What I'm trying to achieve is fill datatable with exchange rates, sourced by API .

So, I managed to construct datatable, but its body is empty and there're no errors in the console, it's just " loading... " message where my data is supposed to be.

Searching for similar topics just didn't get any results. I would be thankful for your help, because I'm banging my head against that wall for 2 days already.

<head> 
  <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script> 
  <script src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>       
  <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css"> 
</head> 
<body> 
  <table id="rates"></table> 
</body>
var key = '8366e7a49e014c729111a0ac6e5c7d9d';
var url = 'https://openexchangerates.org/api/latest.json?app_id=';
var dataTable = $('#rates').DataTable({
  sDom: 't',
  ajax: {
    url: url + key
  },
  columns: [{
    title: 'currency'
  },{
    title: 'rate'
  }]
});

Seems like your data is structured improperly. Each data entry must correspond to DataTables row, so your code should be something like:

 var key = '8366e7a49e014c729111a0ac6e5c7d9d'; var url = 'https://openexchangerates.org/api/latest.json?app_id='; var dataTable = $('#rates').DataTable({ sDom: 't', ajax: { url: url+key, dataSrc: function(data){ let apiData = []; $.each(data.rates, function(index, entry){ apiData.push({currency:index, rate:entry}); }); return apiData.slice(0,10); } }, columns: [ {title:'currency', data:'currency'}, {title:'rate', data:'rate'} ] }); 
 <!doctype html> <html> <head> <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script> <script src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script> <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css"> </head> <body> <table id="rates"></table> </body> </html> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM