【问题标题】:How to display API data from url with jquery datatable如何使用 jquery 数据表从 url 显示 API 数据
【发布时间】:2019-06-02 17:33:52
【问题描述】:

我正在为我的 FiveM 的服务器网站设置一个“统计”页面,我需要有关如何使用 Jquery Datatables 显示数据的帮助

我对API一无所知,所以我用PHP尝试了一些东西,但没有什么真正有用的:/

这是我的代码:

<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title>test-astos</title>
    <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.css">
    <script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.js"></script>
  </head>
  <body>

    <table id="table_id" class="display">
        <thead>
            <tr>
                <th>Column 1</th>
                <th>Column 2</th>
            </tr>
        </thead>
        <tbody>
            <!-- data -->
        </tbody>
    </table>


    <script type="text/javascript">
    $(document).ready( function () {
      $('#table_id').DataTable({
        $.ajax({
          url : 'https://api.top-serveurs.net/v1/servers/SC4VCSEUS3/players-ranking',
          type : 'GET',
          dataType : 'json',
             success : function(json, statut){ // code_html contient le HTML renvoyé
             }
        });
      });
    });
    </script>

  </body>
</html>

我想用 Jquery 数据表显示这些数据 (https://api.top-serveurs.net/v1/servers/SC4VCSEUS3/players-ranking)。

谢谢:)。

【问题讨论】:

    标签: jquery ajax api url datatables


    【解决方案1】:

    首先您忘记使用示例中的 jQuery CDN。并像这样使用。

    <table id="table_id" class="display">
        <thead>
            <tr>
                <th>Votes</th>
                <th>Player Name</th>
            </tr>
        </thead>
        <tbody>
            <!-- data -->
        </tbody>
    </table>
    
    
    <script type="text/javascript">
    $(document).ready( function () {
    
        $.ajax({
            url : 'https://api.top-serveurs.net/v1/servers/SC4VCSEUS3/players-ranking',
            type : 'GET',
            dataType : 'json',
            success : function(data) {
                bindtoDatatable(data.players);
            }
        });
    
    
    
    });
    
    function bindtoDatatable(data) {
            var table = $('#table_id').dataTable({
                "bAutoWidth" : false,
                "aaData" : data,
                "columns" : [ {
                    "data" : "votes"
                }, {
                    "data" : "playername"
                } ]
            })
        }
    </script>
    

    【讨论】:

    • 谢谢,它有效!我认为这更难,非常感谢!
    • 虽然这可行,但这种方法不是最理想的 - 您不应使用外部 ajax 调用来填充您的表,为此目的有一个本机 ajax 选项 - 它为您提供更好的性能(对于动态应用程序,上述方法将需要销毁/重新创建您的 DataTable,或清除/重新填充其内容)并与其余 DataTables API 方法集成。
    • @YevgenGorbunkov 你能为它写一个原生 ajax 的解决方案吗,因为返回的数据不是原生 ajax 的格式
    猜你喜欢
    • 2020-12-11
    • 1970-01-01
    • 2018-05-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-23
    • 2020-02-28
    • 2016-11-28
    相关资源
    最近更新 更多