在JavaScript中读取网站上的TXT文件通常涉及到使用XMLHttpRequest
对象或者更现代的fetch
API来发起HTTP请求获取文件内容。以下是使用这两种方法的基本示例:
XMLHttpRequest
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
var text = xhr.responseText;
console.log(text); // 这里可以处理获取到的文本内容
}
};
xhr.open('GET', 'http://example.com/path/to/yourfile.txt', true);
xhr.send();
fetch
APIfetch('http://example.com/path/to/yourfile.txt')
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok ' + response.statusText);
}
return response.text();
})
.then(text => {
console.log(text); // 这里可以处理获取到的文本内容
})
.catch(error => {
console.error('There has been a problem with your fetch operation:', error);
});
如果你遇到无法读取TXT文件的问题,可以检查以下几点:
确保你的请求符合网站的使用条款,并且尊重版权和隐私政策。
领取专属 10元无门槛券
手把手带您无忧上云