猿问

每 5 秒填充一次 Ajax 数据替换旧数据 jquery

我正在尝试创建一组规则,其中来自 API 的数据在具有 6 个不同 API 的 html 页面中返回。所以我需要的是,每 5 秒显示一次新数据替换旧数据。

这是我到目前为止所做的:

这是小提琴:https : //jsfiddle.net/tohfz61x/3/

在这里我所做的是,添加setInterval function但它没有用。

在这个版本中,它一次获取所有数据并显示循环的最后一个。但我需要一次显示 1 到 6 次。

所以基本上如果第一个结果是 50 美元,几秒钟后,它应该更改为另一个值(例如 30 美元),如 API 中所示。


心有法竹
浏览 276回答 3
3回答

撒科打诨

您可以使用以下条件调用initLoadData()内部 a setTimeout()。var value = 1;initLoadData();function initLoadData() {&nbsp; var ajaxTime = new Date().getTime();&nbsp; var dataURL = "https://adler.blockrize.io/data/" + value;&nbsp; $.getJSON(dataURL, function(response, status, t) {&nbsp; &nbsp; var rewardsEarnedHolder = $('#rewardsEarned');&nbsp; &nbsp; var totalReward = '<span class="price">$' + response.RewardsEarned.TotalReward + '</span>';&nbsp; &nbsp; rewardsEarnedHolder.html(totalReward);&nbsp; &nbsp; console.log(dataURL);&nbsp; &nbsp; value++;&nbsp; &nbsp; if (value <= 6) {&nbsp; &nbsp; &nbsp; setTimeout(function() {&nbsp; &nbsp; &nbsp; &nbsp; initLoadData(value);&nbsp; &nbsp; &nbsp; }, 2000);&nbsp; &nbsp; }&nbsp; });}<script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script><div class="transaction-section bg-dark text-white pb-4">&nbsp; <h2>Transaction History</h2>&nbsp; <div id="rewardsEarned"></div></div>

qq_笑_17

setTimeout()API调用完成后可以调用函数var i = 1;initLoadData();function initLoadData() {&nbsp; var dataURL = "https://adler.blockrize.io/data/" + i;&nbsp; var xhttp = new XMLHttpRequest();&nbsp; xhttp.onreadystatechange = function() {&nbsp; &nbsp; if (this.readyState == 4 && this.status == 200) {&nbsp; &nbsp; &nbsp; let data = JSON.parse(xhttp.responseText);&nbsp; &nbsp; &nbsp; document.getElementById("price").innerHTML = data.RewardsEarned.TotalReward;&nbsp; &nbsp; &nbsp; i = i + 1;&nbsp; &nbsp; &nbsp; if (i <= 6) {&nbsp; &nbsp; &nbsp; &nbsp; setTimeout(function() {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; initLoadData();&nbsp; &nbsp; &nbsp; &nbsp; }, 2000);&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; };&nbsp; xhttp.open("GET", dataURL, true);&nbsp; xhttp.send();}<div class="transaction-section bg-dark text-white pb-4">&nbsp; <h2>Transaction History</h2>&nbsp; <div id="rewardsEarned">$<span id="price">00.00</span></div></div>

元芳怎么了

您可以使用延迟功能,只需在您的代码中进行这些更改替换这个:rewardsEarnedHolder.html(totalReward);有了这个代码rewardsEarnedHolder.html(totalReward).delay(5000);
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答