我想知道如何使用 XMLHttpRequest 加载远程 URL 的内容并将访问站点的 HTML 存储在 JS 变量中。
比如说,如果我想加载和 alert() http://foo.com/bar.php的 HTML,我该怎么做?
我想知道如何使用 XMLHttpRequest 加载远程 URL 的内容并将访问站点的 HTML 存储在 JS 变量中。
比如说,如果我想加载和 alert() http://foo.com/bar.php的 HTML,我该怎么做?
您可以XMLHttpRequest.responseText在等于XMLHttpRequest.onreadystatechange时获得它。XMLHttpRequest.readyStateXMLHttpRequest.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 上运行时,您必须考虑JavaScript 的同源策略。您可能需要考虑在您的域中创建代理脚本。
fetch!它更具可读性且易于定制。所有现代浏览器和 Node 都支持它。这是一个更深入的教程
const url = "https://stackoverflow.com";
fetch(url)
  .then(
    response => response.text() // .json(), .blob(), etc.
  ).then(
    text => console.log(text) // Handle here
  );
您可以选择传递第二个参数,具体取决于请求的需求/类型。
// Example request options
fetch(url, {
  method: 'post', // Default is 'get'
  body: JSON.stringify(dataToPost),
  mode: 'cors',
  headers: new Headers({
    'Content-Type': 'application/json'
  })
})
.then(response => response.json())
.then(json => console.log('Response', json))
在 Node.js 中,您需要fetch使用以下方法导入:
const fetch = require("node-fetch");
如果你想同步使用它(在顶级范围内不起作用):
const json = await fetch(url)
  .then(response => response.json())
  .catch((e) => {});
更多信息:
最简单的方法使用XMLHttpRequest与pure JavaScript。您可以设置,custom header但可以根据需要选择使用。
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 方法发送参数。
请运行以下示例,将获得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();
}
在 中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);