【问题标题】:How to get objects from txt file to use in javascript array?如何从 txt 文件中获取对象以在 javascript 数组中使用?
【发布时间】:2016-05-10 02:40:38
【问题描述】:

我对编码和 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()向服务器请求文件

标签: javascript arrays text


【解决方案1】:

您可以使用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);
        }
    }
}

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

【讨论】:

    【解决方案2】:

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

    您无法在客户端轻松读取文件,因为您不允许直接访问客户端的文件系统。但是,您可以在 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
    
    }
    

    有关文件阅读器的更多信息,请查看docs

    【讨论】:

      【解决方案3】:

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-12-08
        • 1970-01-01
        • 2020-03-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多