简体   繁体   中英

How to send api requests in real time in JS?

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();  

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM