首页 > 解决方案 > 如何实时更新而不是一次又一次地重新加载浏览器?

问题描述

正在学习 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>

标签: javascriptxmlhttprequest

解决方案


您要问的基本上是如何安排您的代码在未来运行。其内置机制是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 秒就有一次更新。但是,你要求realtime。为此,您需要一个不同的工具.. server-sent events

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

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

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

我希望这可以帮助您入门!


推荐阅读