2017-10-08 83 views
0

首先,我是Javascript,Ajax,jQuery,JSON和開發世界的新成員。我正在研究一個我想要顯示Google Books API搜索結果的Web項目。目前我做了只顯示1個結果的代碼,並且它工作正常,但是我在console.log中看到API顯示了一個包含10個項目的數組,因此我想顯示它們。我想顯示所有這些結果,但我不知道如何執行此操作。 我在HTML代碼有一個DIV,這是我的Ajax代碼使用Ajax顯示API的更多搜索結果

$.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循環,但我不知道該怎麼做,或是否會工作

回答

0

你會需要通過它們循環而不是僅僅索引在索引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; 
}