How to send api requests in real time in JS?

家住魔仙堡 提交于 2020-01-24 19:37:05

问题


With this XHR request it would only send request once, if this is done with setTimeout it can repeatedly send request but how to do that in real time? Like on some websites we can see real time bitcoin prices. I read about EventSource but can't understand how it's used.

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

回答1:


With XHR, you can simulate with a Pull by either setTimeout or setInterval, but if you want more instant response, you'll have to set up a WebSocket server.

Not every browser supports websocket, so you'll have to fall back to the Timeout/Interval pulling.

Similar to an XHR object, a WebSocket object defines onopen, onmessage and onerror callbacks.




回答2:


To get the data via EventSource you would need to have a server that implements SSE

Server-sent Events (SSE) is a specification that allows servers to send events directly to clients that subscribe to those events, similar to WebSockets and related server to client push technologies.

An implementation of EventSource looks something like this (take a look at this link):

var evtSource = new EventSource('sse.php');
var eventList = document.querySelector('ul');

evtSource.onmessage = function(e) {
  var newElement = document.createElement("li");

  newElement.textContent = "message: " + e.data;
  eventList.appendChild(newElement);
}

If the event generator script is hosted on a different origin, a new EventSource object should be created with both the URL and an options dictionary.

const evtSource = new EventSource("//api.example.com/ssedemo.php", { withCredentials: true } );

In this case you have a REST API, not a SSE, so the best you can get with that to have real-time information is to use a setTimeout function to repeat the Ajax call every n period of time.



来源:https://stackoverflow.com/questions/58908216/how-to-send-api-requests-in-real-time-in-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!