我想知道如何使用XMLHttpRequest来加载远程URL的内容,并将所访问站点的HTML存储在JS变量中。
比如说,如果我想要加载并alert() http://foo.com/bar.php 的HTML,我该怎么做?
比如说,如果我想要加载并alert() http://foo.com/bar.php 的HTML,我该怎么做?
当XMLHttpRequest.readyState
等于XMLHttpRequest.DONE
时,您可以通过XMLHttpRequest.onreadystatechange
中的XMLHttpRequest.responseText
获取它。
以下是一个示例(不兼容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,而且可以解决一些特定浏览器的内存泄漏或错误,并且在触发ajax请求时减少冗余,您可以使用jQuery。
$.get('http://example.com', function(responseText) {
alert(responseText);
});
请注意,当不在本地主机上运行时,您必须考虑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) => {});
更多信息:
使用纯JavaScript简单地使用XMLHttpRequest
的方法。你可以设置自定义头部信息
,但仅限于根据需求选择。
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);