如何获得XMLHttpRequest的响应?

问题描述 投票:158回答:4

我想知道如何使用XMLHttpRequest加载远程URL的内容,并将访问过的站点的HTML存储在JS变量中。

比方说,如果我想加载并警告()http://foo.com/bar.php的HTML,我该怎么做?

javascript xmlhttprequest
4个回答
247
投票

XMLHttpRequest.responseText等于XMLHttpRequest.onreadystatechange时,你可以通过XMLHttpRequest.readyState中的XMLHttpRequest.DONE得到它。

这是一个例子(与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);

为了更好的交叉浏览器兼容性,不仅可以使用IE6 / 7,而且还可以覆盖某些特定于浏览器的内存泄漏或错误,并且还可以通过触发ajaxical请求来减少冗长,您可以使用jQuery

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

请注意,在不在localhost上运行时,您必须考虑Same origin policy for JavaScript。您可能需要考虑在您的域中创建代理脚本。


22
投票

我建议调查fetch。它是ES5的等价物并使用Promises。它更易读,更容易定制。

const url = "https://stackoverflow.com";
fetch(url)
    .then(
        response => response.text() // .json(), etc.
        // same as function(response) {return response.text();}
    ).then(
        html => console.log(html)
    );

在Node.js中,您需要使用以下命令导入fetch

const fetch = require("node-fetch");

如果要同步使用它(在顶级作用域中不起作用):

const json = await fetch(url)
  .then(response => response.json())
  .catch((e) => {});

更多信息:

Mozilla Documentation

Can I Use (91% Mar 2019)

Matt Walsh Tutorial


15
投票

使用XMLHttpRequestpure JavaScript的简单方法。您可以设置custom header,但可以根据需要使用它。

1. Using POST Method:

window.onload = function(){
    var request = new XMLHttpRequest();
    var params = "UID=CORS&name=CORS";

    request.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            console.log(this.responseText);
        }
    };

    request.open('POST', 'https://www.example.com/api/createUser', true);
    request.setRequestHeader('api-key', 'your-api-key');
    request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    request.send(params);
}

您可以使用POST方法发送params。

2. Using GET Method:

请在下面的示例中运行,并获得JSON响应。

window.onload = function(){
    var request = new XMLHttpRequest();

    request.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            console.log(this.responseText);
        }
    };

    request.open('GET', 'https://jsonplaceholder.typicode.com/users/1');
    request.send();
}

14
投票

XMLHttpRequest中,使用XMLHttpRequest.responseText可能会像下面一样引发异常

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

从XHR访问响应的最佳方式如下

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);
© www.soinside.com 2019 - 2024. All rights reserved.