Access partial response using AJAX or WebSockets?

I use client-side JavaScript code to pull a lot of JSON data from a web server via HTTP GET. The amount of data can be large, say, 50 MB. This happens on the local network, so this is not a problem, but it still takes about ten seconds.

To make my interface more responsive, I would like to process the response in pieces, showing the data in the user interface as soon as it becomes available (say, in MB or second). Browser compatibility is not a problem; while it works with the latest Chrome and Firefox, everything will be fine. However, I cannot change the server code.

Can this be done using XMLHttpRequest or WebSockets or any other technology that I have not heard about?

XMLHttpRequest.responseTextis not explicitly empty until state LOADING:

The responseText attribute should return the result of the following steps:

  • If the state does not load or DONE returns an empty string and completes these steps.
  • Gets the body of the response object of the text response.

But I believe that buffering will occur at different stages along the way, so will it work if I set a timer for periodic polling responseText?

As far as I can tell, WebSockets requires a special server-side protocol, so they are missing.

Limitation: I cannot change the server code.

+5
source share
1 answer

, textarea

? xmlHttpRequestInstance.onreadystatechange, ? xmlHttpRequestInstance.readystate 3, xmlHttpRequestInstance.responseText . readistate , , .

, , , :

var xhr = new XMLHttpRequest();
var lastPos = 0;
xhr.onreadystatechange = function() {
  if(xhr.readystate === 3) {
    var data = xhr.responseText.substring(lastPos);
    lastPos = xhr.responseText.length;

    process(data);
  } 
};
// then of course do `open` and `send` :)

, , onreadystatechange. IE, Chrome, Safari Firefox.

+5

All Articles