【问题标题】:Display more search results of API with Ajax使用 Ajax 显示更多 API 搜索结果
【发布时间】:2017-10-08 16:16:54
【问题描述】:

首先我是 Javascript、Ajax、jQuery、JSON 和开发世界的新手。我正在开发一个网络项目,我想显示来自 Google Books API 的搜索结果。目前,我编写的代码仅显示 1 个结果并且运行良好,但我在 console.log 中看到 API 结果显示了一个包含 10 个以上项目的数组,我想显示它们。我想显示所有这些结果,但我不知道该怎么做。 我的 HTML 代码中有一个 DIV,这是我的 Ajax 代码

$.ajax({
    url: API + libroBuscado,
    success: function(data) {


  var componente = `<div class="card" style="width: 20rem;">
    <div class="card-body">
      <h4 class="card-title">Card title</h4> 
      <h4 class="precio">$</h4>
      <h6 class="card-subtitle mb-2 text-muted">Card subtitle</h6>
      <p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's content.</p>
      <a href="#" class="card-link">Descarga un adelanto</a>
      <a href="#" class="card-link">Comprar</a>

    </div>
  </div>`;

  var titulo = data.items[0].volumeInfo.title;
  var venta = data.items[0].saleInfo.saleability;
  var precio = "ARS $" + data.items[0].saleInfo.listPrice.amount;
  var autor = data.items[0].volumeInfo.authors;
  var sinopsis = data.items[0].volumeInfo.description;
  var descarga = data.items[0].accessInfo.webReaderLink;
  var compra = data.items[0].saleInfo.buyLink;

  $(".col-12").html(componente);
  $(".card-title").text(titulo);
  $(".precio").text(precio);
  $(".card-subtitle").text(autor);
  $(".card-text").text(sinopsis);
  $(".card-link:nth-of-type(0)").attr("href" + descarga);
  $(".card-link:nth-of-type(1)").attr("href" + compra);
  console.log(data);
},

error: function(error) {
  console.log(error);
}


 });
});

我正在考虑创建一个 for 循环,但我不知道该怎么做,也不知道它是否可行

【问题讨论】:

    标签: javascript jquery json ajax api


    【解决方案1】:

    您需要遍历它们,而不是只调用索引 0 处的项目。

    类似的东西。

    var titulo;
    var venta;
    var precio;
    var autor;
    var sinopsis;
    var descarga;
    var compra;
    
    for (i = 0; i < data.items.length; i++) { 
        titulo = data.items[i].volumeInfo.title;
        venta = data.items[i].saleInfo.saleability;
        precio = "ARS $" + data.items[i].saleInfo.listPrice.amount;
        autor = data.items[i].volumeInfo.authors;
        sinopsis = data.items[i].volumeInfo.description;
        descarga = data.items[i].accessInfo.webReaderLink;
        compra = data.items[i].saleInfo.buyLink;
    }
    

    【讨论】:

      猜你喜欢
      • 2019-05-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-05
      • 2016-06-26
      • 2017-12-30
      • 1970-01-01
      • 2015-04-04
      相关资源
      最近更新 更多