如何在在线javascript中调用json api数据?

时间:2019-03-22 02:19:26

标签: javascript jquery json ajax

我想创建一个表并搜索过滤器,数据取自此处 https://swapi.co/api/planets/?format=json。谁能举例说明如何通过json api检索数据以及如何创建过滤器搜索?

2 个答案:

答案 0 :(得分:2)

Bootstrap jQuery示例将有助于过滤。

  

https://www.w3schools.com/bootstrap/bootstrap_filters.asp

为了访问API,您需要创建一个AJAX(XHR,Http Requester等)调用以检索数据。如果您使用jQuery,这很容易:

$.ajax({
  dataType: 'json', // Expecting JSON
  url: 'https://swapi.co/api/planets/?format=json', // Data endpoint
  cache: true, // Cache the request for testing purposes
  success: function(data) {
    populateTable(data.results); // On success, access the data
  }
});

对于填充表,您需要从结果中的一个数据项中获取字段并对其进行排序。您还可以忽略某些字段,如下所示。

$('#myTable')
  .append($('<thead>')
    .append($('<tr>')
      .append(fields.map(field => $('<th>').addClass('text-center').text(field)))))
  .append($('<tbody>')
    .append(data.map(result => $('<tr>')
      .append(fields.map(field => $('<td>').text(result[field]))))));

更新:如果要使用加载蒙版,则需要在结果容器内创建一个绝对定位的div。请求数据时,请显示掩码。收到响应后,将其隐藏。

<div class="loadable">
  <div class="loading-mask"></div>
  <table id="myTable" class="table table-bordered table-striped"></table>
</div>
.loadable {
  position: relative;
  overflow: scroll;
}

.loadable > .loading-mask,
.loadable > table {
  position: absolute;
}

演示

let ignoreFields = [ 'created', 'edited', 'films', 'residents', 'url' ],
    sortField    = 'name';

$(function() {
  $('.loading-mask').show(); // Show mask before request
  $.ajax({
    dataType: 'json',
    url: 'https://swapi.co/api/planets/?format=json',
    cache: true,
    success: function(data) {
      populateTable(data.results);
      $('.loading-mask').hide(); // Hide mask after response
    },
    failure: function(data) {
      $('.loading-mask').hide(); // Hide mask after response
    }
  });
  $('#myInput').on('keyup', onFilter);
});

function populateTable(data) {
  data.sort((a, b) => {
    return a[sortField].toLowerCase().localeCompare(b[sortField].toLowerCase());
  });

  var fields = Object.keys(data[0]).sort((a, b) => {
    if (a === sortField) return -1;
    if (b === sortField) return 1;
    return a.toLowerCase().localeCompare(b.toLowerCase());
  }).filter(x => ignoreFields.indexOf(x) === -1);

  $('#myTable')
    .append($('<thead>')
      .append($('<tr>')
        .append(fields.map(field => $('<th>').addClass('text-center').text(field)))))
    .append($('<tbody>')
      .append(data.map(result => $('<tr>')
        .append(fields.map(field => $('<td>').text(result[field]))))));
}

function onFilter(e) {
  let value = $(this).val().toLowerCase();
  $('#myTable tbody tr').filter(function() {
    $(this).toggle($(this).text().toLowerCase().indexOf(value) > -1);
  });
}
.loadable {
  position: relative;
  width: 100%;
  height: 300px;
  overflow: scroll;
}

.loadable > .loading-mask,
.loadable > table {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 300px; /* Same as its parent */
}

.loading-mask {
  display: none; /* Hidden by default */
  background-color: rgba(0, 0, 0, 0.5);
  background-image: url('https://i.imgur.com/lW8P6HP.gif');
  background-repeat: no-repeat;
  background-position: center;
  z-index: 1000;
}

#myInput {
  margin-bottom: 0.667em;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">

<div class="container">
  <h2>Filterable Table</h2>
  <p>Type something in the input field to search the table for first names, last names or emails:</p>
  <input class="form-control" id="myInput" type="text" placeholder="Search..">
  <div class="loadable">
    <div class="loading-mask"></div>
    <table id="myTable" class="table table-bordered table-striped"></table>
  </div>
  <p>Note that we start the search in tbody, to prevent filtering the table headers.</p>
</div>

答案 1 :(得分:1)

您可以将Datatables库与Ajax sourced dataServer-side processing一起用于需求创建表以及搜索,过滤来自API的数据。

有带有示例javascript代码的参考链接

https://datatables.net/examples/data_sources/server_side.html https://datatables.net/examples/data_sources/ajax.html

更新:

我添加了带有用于数据表的脚本和HTML的演示。您可以在返回的对象dataSrc property中将results property设置为dataSrc: 'results'

$('#example').DataTable({
    ajax: {
        url: 'https://swapi.co/api/planets/?format=json',
        dataSrc: 'results'
    },
    columns: [
      { data: "name" }, 
      { data: "climate" }, 
      { data: "diameter" },
      { data: "gravity" },
      {data: "orbital_period"},
      {data: "population"}
    ]
})

enter image description here

$('#example').DataTable({
    ajax: {
        url: 'https://swapi.co/api/planets/?format=json',
        dataSrc: 'results'
    },
    columns: [
      { data: "name" }, 
      { data: "climate" }, 
      { data: "diameter" },
      { data: "gravity" },
      {data: "orbital_period"},
      {data: "population"}
    ]
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.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" >
<table id="example" class="display" style="width:100%">
        <thead>
            <tr>
                <th>name</th>
                <th>climate</th>
                <th>diameter</th>
                <th>gravity</th>
                <th>orbital_period</th>
                <th>population</th>
                
            </tr>
        </thead>
        <tfoot>
            <tr>
                <th>name</th>
                <th>climate</th>
                <th>diameter</th>
                <th>gravity</th>
                <th>orbital_period</th>
                 <th>population</th>
            </tr>
        </tfoot>
    </table>