请帮帮我! 我有剧本:
var titles =[];
titles.push('I want file txt in here');
我无法将txt文件放入titles.push中,所以我需要一些帮助!
function readTextFile(){
var rawFile = new XMLHttpRequest();
rawFile.open("GET", "text.txt", false);
rawFile.onreadystatechange = function (){
if(rawFile.readyState === 4){
if(rawFile.status === 200 || rawFile.status == 0){
var allText = rawFile.responseText;
console.log(allText);
}
}
}
rawFile.send(null);
}
答案 0 :(得分:0)
我没有准备好显示的文字文件,因此我使用了您应该阅读的有关XMLHttpRequest.responseText的内容,您不想使用onreadystatechange
,但可能xhr.onload
我留下了一些console.log()s
1}}在代码中,你可以玩它。
var titles =[];
titles.push('I want file txt in here');
var xhr = new XMLHttpRequest();
xhr.open('GET', 'https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/responseText', true);
xhr.responseType = 'text';
xhr.onload = function () {
if (xhr.readyState === xhr.DONE) {
if (xhr.status === 200) {
//console.log(xhr.response);
//console.log(xhr.responseText);
// not needed but do not want to push the entire page
// to titles so lets find just one title
var parser = new DOMParser();
var doc = parser.parseFromString(xhr.responseText, "text/html");
var title = doc.querySelector('h1');
// console.log(title);
titles.push(title);
logTitles();
}
}
};
xhr.send(null);
function logTitles() {
console.log(titles);
};