weixin_33733810 2015-12-31 09:34 采纳率: 0%
浏览 14

读取部分远程文件[重复]

This question already has answers here:
                </div>
            </div>
                    <div class="grid--cell mb0 mt4">
                        <a href="/questions/7686827/how-can-i-add-a-custom-http-header-to-ajax-request-with-js-or-jquery" dir="ltr">How can I add a custom HTTP header to ajax request with js or jQuery?</a>
                            <span class="question-originals-answer-count">
                                (9 answers)
                            </span>
                    </div>
            <div class="grid--cell mb0 mt8">Closed <span title="2016-01-02 22:31:40Z" class="relativetime">4 years ago</span>.</div>
        </div>
    </aside>

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?

</div>
  • 写回答

1条回答 默认 最新

  • weixin_33670786 2015-12-31 09:37
    关注

    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.

    评论

报告相同问题?