如何在Javascript中正确实现API响应的setInterval ?



我正在获得API响应并在HTML表中添加响应。现在我正在尝试setInterval,但setInterval没有正确设置。代码如下:

const settings = {
"async": true,
"crossDomain": true,
"url": "https://datasource.com/price?list",
"method": "GET",
"headers": {
"xxxxxxxxxxxxxxxxxx",
"xxxxxxxxxxxxxxxx"
}
};
setInterval(function() {
$.ajax(settings).done(function(response) {
var sdata = '';
$.each(response, function(key, value) {
sdata += '<tr>';
sdata += '<td>' + value.symbol + '</td>';
sdata += '<td>' + value.lastPrice + '</td>';
sdata += '<td>' + value.change + '</td>';
sdata += '<td>' + value.pChange + '</td>';
sdata += '<td>' + value.open + '</td>';
sdata += '<td>' + value.dayHigh + '</td>';
sdata += '<td>' + value.dayLow + '</td>';
sdata += '<td>' + value.previousClose + '</td>';
sdata += '<td>' + value.perChange30d + '</td>';
sdata += '<td>' + value.perChange365d + '</td>';
sdata += '<td>' + value.lastUpdateTime + '</td>';
sdata += '</tr>';
});
$('#shares').html(sdata);
//console.log(response);
});
}, 5000);
<table id="shares">
<tr>
<th>NAME</th>
<th>LTP</th>
<th>CHANGE</th>
<th>CHG %</th>
<th>OPEN</th>
<th>HIGH</th>
<th>LOW</th>
<th>CLOSE</th>
<th>30 DAY ROI</th>
<th>1 YR ROI</th>
<th>UPDATED ON</th>
</tr>

</table>

如何在上面提到的javascript代码中实现一个工作setInterval ?

const settings = {
"async": true,
"crossDomain": true,
"url": "https://datasource.com/price?list",
"method": "GET",
"headers": {
"xxxxxxxxxxxxxxxxxx",
"xxxxxxxxxxxxxxxx"
}
};
setInterval(function() {
$.ajax(settings).done(function (response) {
var sdata = '';
$('#shares').empty();
$.each(response, function(key,value){
sdata += '<tr>';
sdata += '<td>'+value.symbol+'</td>';
sdata += '<td>'+value.lastPrice+'</td>';
sdata += '<td>'+value.change+'</td>';
sdata += '<td>'+value.pChange+'</td>';
sdata += '<td>'+value.open+'</td>';
sdata += '<td>'+value.dayHigh+'</td>';
sdata += '<td>'+value.dayLow+'</td>';
sdata += '<td>'+value.previousClose+'</td>';
sdata += '<td>'+value.perChange30d+'</td>';
sdata += '<td>'+value.perChange365d+'</td>';
sdata += '<td>'+value.lastUpdateTime+'</td>';
sdata += '</tr>';
});
$('#shares').html(sdata);
}); }, 5000);
table {
border: 1px;
}
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<title></title>
</head>
<body>

<table>
<thead>
<tr>
<th>NAME</th>
<th>LTP</th>
<th>CHANGE</th>
<th>CHG %</th>
<th>OPEN</th>
<th>HIGH</th>
<th>LOW</th>
<th>CLOSE</th>
<th>30 DAY ROI</th>
<th>1 YR ROI</th>
<th>UPDATED ON</th>
</tr>
</thead>
<tbody id="shares">

</tbody>
</table>

.append(sdata)追加数据(意料之中:))

如果您不想附加,而是替换整个内容,请使用.html(sdata)

更新小提琴

相关内容

  • 没有找到相关文章

最新更新