【问题标题】:Insert data from API into DOM将 API 中的数据插入 DOM
【发布时间】:2016-03-30 09:12:52
【问题描述】:

我从 API 中检索数据,我想在我的引导布局中获取它。

$.ajax({
  url: 'https://api.import.io/store/connector/b5caf0ef-1e6b-4fba-9fa4-21e475196673/_query?input=webpage/url:http%3A%2F%2Fnuzzel.com%2FWAStatzz%3Fsort%3Dfriends%26when%3D2&&_apikey=<myKey>'
}).done(function(data) {
  console.log(data);

  var html = "";
  $.each(data.results, function(index, item) {
    html += "<div class='row'>";
    html += "<div class='item'><a href='" + item['headline'] + "'>" + item['headline/_text'] + "</a></div>";
    html += "<span class='item-description'>" + item.description + "</span>";
    html += "</div>";
  });

  setTimeout(function() {
    $(".container").append(html);
  }, 1500);
});

我试过这个,但它不起作用?为什么?

【问题讨论】:

  • 具体是什么不起作用?数据获取或修改 HTML?此外,您的网址末尾似乎有一个额外的&amp;。是错字吗?
  • 哦,千万不要将您的 API 密钥放到公开帖子中 - 该信息应该只对您保密。我从帖子中删除了它,您可能应该生成一个新的。
  • @MatthewHerbst 好的,我忘记了 api 密钥,谢谢!
  • @MatthewHerbst 获取数据就像一个魅力,但我想要一个带有 .row 和 .item 的引导布局

标签: javascript jquery import.io


【解决方案1】:

好吧,只需将容器添加到应添加标记的 DOM 中即可。

<div class="js-table-container"></div>

然后将html添加到这个容器中

var html = "";
$.each(data.results, function(index, item) {
html += "<div class='row'>";
html += "<div class='item'><a href='" + item['headline'] + "'>" + item['headline/_text'] + "</a></div>";
html += "<span class='item-description'>" + item.description + "</span>";
html += "</div>";
});
$('.js-table-container').html(html);

如果我正确理解您的问题,就是这样。

【讨论】:

    【解决方案2】:

    如果你在 Dom 中的元素之后或之前有什么数据,请使用 jquery insertAfter 或 insertBefore。为什么要使用超时功能? 处理后可以直接添加到Dom中。

    >     $.ajax({
    >       url: 'https://api.import.io/store/connector/b5caf0ef-1e6b-4fba-9fa4-21e475196673/_query?input=webpage/url:http%3A%2F%2Fnuzzel.com%2FWAStatzz%3Fsort%3Dfriends%26when%3D2&&_apikey=<myKey>'
    >     }).done(function(data) {
    >       console.log(data);
    >     
    >       var html = "";
    >       $.each(data.results, function(index, item) {
    >         html += "<div class='row'>";
    >         html += "<div class='item'><a href='" + item['headline'] + "'>" + item['headline/_text'] + "</a></div>";
    >         html += "<span class='item-description'>" + item.description + "</span>";
    >         html += "</div>";
    >       });
    >     // if you want to load all data inside this container use html
    >         $(".container").html(html);
    >     // if you want to load after this
    >      $(".container").insertAfter(html);
    >     // if you want before this
    >      $(".container").insertBefore(html);

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-02-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-02
      • 2018-11-18
      • 1970-01-01
      • 2019-08-11
      相关资源
      最近更新 更多