How to get the response of XMLHttpRequest?

后端 未结 4 1621
挽巷
挽巷 2020-11-22 06:23

I\'d like to know how to use XMLHttpRequest to load the content of a remote URL and have the HTML of the accessed site stored in a JS variable.

Say, if I wanted to l

4条回答
  •  终归单人心
    2020-11-22 07:21

    You can get it by XMLHttpRequest.responseText in XMLHttpRequest.onreadystatechange when XMLHttpRequest.readyState equals to XMLHttpRequest.DONE.

    Here's an example (not compatible with IE6/7).

    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function() {
        if (xhr.readyState == XMLHttpRequest.DONE) {
            alert(xhr.responseText);
        }
    }
    xhr.open('GET', 'http://example.com', true);
    xhr.send(null);
    

    For better crossbrowser compatibility, not only with IE6/7, but also to cover some browser-specific memory leaks or bugs, and also for less verbosity with firing ajaxical requests, you could use jQuery.

    $.get('http://example.com', function(responseText) {
        alert(responseText);
    });
    

    Note that you've to take the Same origin policy for JavaScript into account when not running at localhost. You may want to consider to create a proxy script at your domain.

提交回复
热议问题