如何实时更新,而不是一次又一次地重新加载浏览器?

问题描述 投票:1回答:1

我正在学习xhr,如何在浏览器上实时保持价格加载?当我们向api发送GET请求时,我们收到一个有价格的json响应,我不想一次又一次地重新加载浏览器标签来检查价格,我想让它实时更新,怎么办?

<!DOCTYPE html>
<html>
<head>
<title>TEST</title>
</head>
<body>
<script type="text/javascript">
var xhr = new XMLHttpRequest();
xhr.onload  = function(){
    document.write(this.responseText)
};
xhr.open("GET","https://api.coindesk.com/v1/bpi/currentprice/USD.json",true);
xhr.send();
</script>
</body>
</html>
javascript xmlhttprequest
1个回答
0
投票

你问的基本上是如何安排你的代码在未来运行。其中的内置机制是运行一次的setTimeout()和运行多次的setInterval()。例如,您可以:

setInterval(function () {
  var xhr = new XMLHttpRequest();
  xhr.onload  = function(){
    document.write(this.responseText)
  };
  xhr.open("GET","https://api.coindesk.com/v1/bpi/currentprice/USD.json",true);
  xhr.send();
}, 10 * 1000);

这会每10秒运行一次代码。 (10乘以1000毫秒。)但是有一个问题,因为你的GET请求可能需要超过10秒才能完成。在糟糕的移动连接和高延迟链路(例如卫星用户的链路)上尤其如此。要解决该问题,您需要使用setTimeout(),并在第一个请求完成后触发代码运行。您应该确保还包括错误情况,因为如果只有一个错误,您不希望循环停止。为了使这一切更简单,我将切换到使用Fetch API。 (Fetch是你现在应该使用的东西。它比XHR更强大,并得到浏览器的良好支持。)

function updatePrices() {
  return fetch('https://api.coindesk.com/v1/bpi/currentprice/USD.json').then({
    if (res.ok) {
      throw new Error('Request failed');
    }
    return res.json()
  }).then((data) => {
    console.log(data);
    setTimeout(updatePrices, 10 * 1000);
  }).catch((e) => {
    setTimeout(updatePrices, 5 * 1000); // If fail, try again sooner
  });
}
updatePrices();

现在,您每10秒钟就有一次更新。但是,你要求实时。为此,你需要一个不同的工具.. server-sent events

如果您控制服务器,则可以选择支持这种简单的基于文本的协议。这允许服务器在更新时立即将数据推送给您。在客户端上设置事件源非常简单:

const eventSource = new EventSource('https://example.com/bitcoin-prices');
eventSource.addEventListener('message', (e) => {
  console.log(e.data);
});

如果连接丢失,EventSource甚至会重新连接。

我希望这可以帮助你开始!

© www.soinside.com 2019 - 2024. All rights reserved.