JavaScript 中获取 URL 页面内容有多种方法,以下是一些基础概念和相关技术:
fetch('https://example.com/page')
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.text();
})
.then(data => {
console.log(data); // 这里是页面的 HTML 内容
})
.catch(error => {
console.error('There has been a problem with your fetch operation:', error);
});
var xhr = new XMLHttpRequest();
xhr.open('GET', 'https://example.com/page', true);
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
console.log(xhr.responseText); // 这里是页面的 HTML 内容
}
};
xhr.send();
catch
块中添加错误处理逻辑,如重试机制或显示错误信息给用户。Content-Type
响应头,并根据实际类型使用相应的方法(如 response.json()
)来处理数据。通过上述方法和注意事项,可以有效地在 JavaScript 中获取和处理 URL 页面内容。
领取专属 10元无门槛券
手把手带您无忧上云