How to get the response of XMLHttpRequest?

后端 未结 4 1624
挽巷
挽巷 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:13

    In XMLHttpRequest, using XMLHttpRequest.responseText may raise the exception like below

     Failed to read the \'responseText\' property from \'XMLHttpRequest\': 
     The value is only accessible if the object\'s \'responseType\' is \'\' 
     or \'text\' (was \'arraybuffer\')
    

    Best way to access the response from XHR as follows

    function readBody(xhr) {
        var data;
        if (!xhr.responseType || xhr.responseType === "text") {
            data = xhr.responseText;
        } else if (xhr.responseType === "document") {
            data = xhr.responseXML;
        } else {
            data = xhr.response;
        }
        return data;
    }
    
    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function() {
        if (xhr.readyState == 4) {
            console.log(readBody(xhr));
        }
    }
    xhr.open('GET', 'http://www.google.com', true);
    xhr.send(null);
    

提交回复
热议问题