2

There is a remote file that we want to read part of it, using Ajax. How can we do it just using JS, without server side techs like PHP?

I think I need to use HTTP Range header, but how to set it with Ajax? Is it possible to set HTTP headers in Ajax at all?

huysentruitw
  • 27,376
  • 9
  • 90
  • 133
user5483434
  • 492
  • 7
  • 17
  • 2
    [How can I add a custom HTTP header to ajax request with js or jQuery?](http://stackoverflow.com/questions/7686827/how-can-i-add-a-custom-http-header-to-ajax-request-with-js-or-jquery) – peppeocchi Dec 31 '15 at 09:41

1 Answers1

2

You can set headers on XML requests via setRequestHeader, e.g. if xhr is an XMLHttpRequest instance:

xhr.setRequestHeader('HeaderName', 'HeaderValue');

I just tested it, and this gave me the first 56 characters of the file I requested:

var xhr = new XMLHttpRequest();
xhr.open("get", "thefile");
xhr.setRequestHeader("Range", "bytes=0-100");
xhr.onreadystatechange = function() {
    if (xhr.readyState == 4) {
        $("<p>").text("status = " + xhr.status + ", length = " + xhr.responseText.length + ", text = " + xhr.responseText).appendTo(document.body);
    }
};
xhr.send();

Note that the status comes back as 206 (Partial Content), not 200.

Why 56 characters? Probably a bytes vs. characters thing in my test.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875