JavaScript jQuery中的两个嵌套ajax请求



我的代码有问题。我想在我的网站上创建一个加密货币排名。我使用API在一面得到一个标志,符号,指数,价格等加密货币。现在我有一个问题,因为这个API没有提供足够的信息。我想使用第二个API来获取有关其他值的信息。但问题是,如何在嵌套ajax请求中做到这一点?我使用foreach循环来显示crypto的值。

var getCurrencyList = function() {
$.ajax({
url: 'https://chasing-coins.com/api/v1/top-coins/200',
dataType: 'json',
type: 'get',
}).done(function(res) {
//here I want use second api call
$.ajax({
url: 'https://pro.coinmarketcap.com/api/v1', //Simple link, because you need api key
dataType: 'json',
type: 'get',
}).done(function(res) {
var data;
Get res.data
}
})
var dataArray = []; dataArray = Array.from(Object.keys(res), k => res[k]);
dataArray.forEach((item, index) => {
var row = document.createElement('tr');
row.className = 'row-coin';
row.innerHTML = `
<th scope='row'>${index}</th>
<td class='logoNameCoin'><img width='25px ' src='https://chasing-coins.com/api/v1/std/logo/${item.symbol}'/> <p>${item.symbol}</p></td>
<td><p>$ ${numberRound(item.cap)} </p></td>
<td><p>$ ${parseFloat(Math.round(item.price * 100) / 100).toFixed(2)}</p></td>
<td><p>${item.change.hour > 0 ? '<span style="color: green;">' + "+" + item.change.hour + '</span>' : '<span style="color: red;">' + item.change.hour}</span></p></td>
<td><p>${item.change.day > 0 ? '<span style="color: green;">' + "+" + item.change.day + '</span>' : '<span style="color: red;">' + item.change.day}</span> </p></td>
<td> // I Need to put data from second request here</td>
document.querySelector('.loading').style.display = 'none';
document.querySelector('.table-content').appendChild(row);

});
});
}

您必须在"完成功能"中进行处理

var getCurrencyList = function(){
$.ajax({
url: 'https://chasing-coins.com/api/v1/top-coins/200',
dataType: 'json',
type: 'get',
}).done(function(res){

//here I want use second api call
$.ajax({
url: 'https://pro.coinmarketcap.com/api/v1', //Simple link, because you need api key
dataType: 'json',
type: 'get',
}).done(function(res){
var dataArray = [];
dataArray = Array.from(Object.keys(res), k=>res[k]);
dataArray.forEach((item,index) =>{
var row = document.createElement('tr');

row.className = 'row-coin';
row.innerHTML = `
<th scope='row'>${index}</th>
<td class='logoNameCoin'><img width='25px ' src='https://chasing- 
coins.com/api/v1/std/logo/${item.symbol}'/> <p>${item.symbol}</p></td>
<td><p>$ ${numberRound(item.cap)} </p></td>
<td><p>$ ${parseFloat(Math.round(item.price * 100) / 100).toFixed(2)}</p> 
</td>
<td><p>${item.change.hour > 0 ? '<span style="color: green;">' + "+" + 
item.change.hour + '</span>' : '<span style="color: red;">' + item.change.hour} 
</span></p></td>
<td><p>${item.change.day > 0 ? '<span style="color: green;">' + "+" + 
item.change.day + '</span>' : '<span style="color: red;">' + item.change.day} 
</span> </p></td>
<td> // I Need to put data from second request here</td>
`
document.querySelector('.loading').style.display = 'none';
document.querySelector('.table-content').appendChild(row);

});
});
}
})

最新更新