我通過一個 api 來給我 json 格式的資訊,接收貨幣的價格并使用 JavaScript 將其顯示在螢屏上。當然,我將這些放在一個函式中,讓 ajax 每 x 秒更新一次資訊。
我需要一個獲取當前價格值的代碼,接收到的下一個價格值將這兩者進行比較,如果新價格高于前一個價格,例如,背景變為綠色或發出警報。如果小于前一個,背景會變成紅色。
我的代碼:
var auto_refresh = setInterval(
function() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var myObj = JSON.parse(this.responseText);
document.getElementById("bids1").innerHTML = myObj.BTCUSDT['bids']['0']['0'];
}
};
xmlhttp.open("GET", "all.json", true);
xmlhttp.send();
}, 1000);
uj5u.com熱心網友回復:
不要在 Ajax 上使用間隔
let val = 0;
const bids = document.getElementById("bids1");
function getData() {
fetch('all.json')
.then(response => response.json())
.then(data => {
const newVal = myObj.BTCUSDT['bids']['0']['0'];
bids.innerHTML = newVal
bids.classList.toggle("green",val > newVal)
bids.classList.toggle("red",val < newVal)
val = newVal;
setTimeout(getData,1000)
})
}
getData()
uj5u.com熱心網友回復:
更正
請參閱上面 mplungjan 的答案,以獲得更正確的方法。雖然按照我指定的添加變數是處理此問題的好方法,但您現有的定期檢索資料的方法不是正確的方法,您應該考慮按照 mplungjan 的指定更改它!
原始答案
我通常建議使用全域變數(或至少在您的函式之外)來保持當前價格,并將檢索到的值與此值進行比較。
// initialize the current price
let currentPrice = 0;
var auto_refresh = setInterval(function () {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
var myObj = JSON.parse(this.responseText);
let newPrice = myObj.BTCUSDT['bids']['0']['0'];
if (newPrice > currentPrice) {
// alert, set some other attribute, etc.
}
// update the global variable and the HTML
currentPrice = newPrice;
document.getElementById("bids1").innerHTML = currentPrice;
}
};
xmlhttp.open("GET", "all.json", true);
xmlhttp.send();
}, 1000);
根據您的要求,您當然也可以在您的 http 請求處理程式中進行不同的檢查和比較。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/406639.html
標籤:
上一篇:使用Vuex和axios發送請求時Vue-cli專案資料更新延遲
下一篇:有效負載未傳遞給處理程式
