如何从txt文件中获取要在javascript数组中使用的对象

How to get objects from txt file to use in javascript array?

本文关键字:数组 javascript 对象 txt 文件 获取      更新时间:2023-09-26

我对编码和javascript非常陌生;就在几天后。我想知道是否有一种方法可以从文本文件(用行分隔)导入对象,以便在我的数组中使用:replyText。以下是我正在使用的内容:

// Variables
var theButton = document.getElementById("theButton");
var mainText = document.getElementById("mainText");
var replyText = [...,...,...,...,];
var i = 0;
// Functions
function nextText() {
  mainText.innerHTML = replyText[i++ % replyText.length];
}
// MAIN SCRIPT
theButton.onclick = function() {
    nextText();
};

您可以使用XMLHttpRequest来获取.txt文件,只需通过它的路径。

var file = new XMLHttpRequest();
file.open("GET", "file:/../file.txt", false);
file.onreadystatechange = function () {
    if (file.readyState === 4) {
        if (file.status === 200 || file.status == 0) {
            var text = file.responseText;
            alert(text);
        }
    }
}

EDIT:必须通过绝对路径file:///C:/your/path/to/file.txt

用于客户端/浏览器端文件读取:

您无法轻松读取客户端上的文件,因为不允许直接访问客户端的文件系统。但是,您可以在HTML标记中放置文件类型的input元素,客户端可以通过该元素加载文件供程序处理。例如:

<input type="file" id="file" onchange="readFile()" />

现在,当客户端选择要使用的文件时,将调用readFile()函数,该函数将读取并处理该文件。这里有一个例子:

function readFile() {
    var file = document.getElementById('file').files[0]; // select the input element from the DOM
    var fileReader = new FileReader(); // initialize a new File Reader object
    fileReader.onload(function() { // call this function when file is loaded
        console.log(this.result); // <--- You can access the file data from this variable
        // Do necessary processing on the file
    });
    fileReader.readAsText(file); // Read the file as text
}

有关文件读取器的更多信息,请查看文档。

要添加到Paulo的解决方案中,请阅读下面的换行符(换行符)拆分字符串

var replyText = text.split("'n"); // "'n" is new line character