Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/423.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
读取txt文件并放入javascript数组_Javascript_Html_Arrays - Fatal编程技术网

读取txt文件并放入javascript数组

读取txt文件并放入javascript数组,javascript,html,arrays,Javascript,Html,Arrays,我想知道如何读取txt文件并将其内容放入javascript数组中 我的txt文件看起来像这样。 [Skin1]、[skin2]、[skin3]等 我只是想从txt文件中获取数组内容,而不是将数组写入实际的html文件 我对javascript相当陌生,不知道如何做到这一点 另外,我的html和txt文件将在同一台服务器上。如果这有区别的话 我非常感谢您提供一个示例代码,提前感谢。如评论中所述,如果文本文件用JSON编码,这将更有效地实现。但是,在不知道文本文件是如何生成的情况下,我不能推荐一种

我想知道如何读取txt文件并将其内容放入javascript数组中

我的txt文件看起来像这样。 [Skin1]、[skin2]、[skin3]等

我只是想从txt文件中获取数组内容,而不是将数组写入实际的html文件

我对javascript相当陌生,不知道如何做到这一点

另外,我的html和txt文件将在同一台服务器上。如果这有区别的话


我非常感谢您提供一个示例代码,提前感谢。

如评论中所述,如果文本文件用JSON编码,这将更有效地实现。但是,在不知道文本文件是如何生成的情况下,我不能推荐一种将其生成为JSON的方法,因此下面介绍如何解析当前文件

假设您正在前端读取文本文件的内容,您将使用XMLHttpRequest异步获取文本文件的内容。一旦收到文件内容,就可以将其转换为数组。在您提供的文本文件格式为[Skin1]、[skin2]、[skin3]的特定情况下,您将删除第一个[和最后一个],然后按轮廓分割]、


您的文本文件的语法不是有效的JSON。我建议修复生成文本文件的任何内容,以保存有效的JSON,然后您可以使用JSON.parse立即将其文本转换为数组。可能与@CertainPerformance重复问题中与JSON无关。@DanielBeck否,但如果文本发生更改所以它是JSON,OP使用它会容易得多。我正在寻找指导,我真的不知道如何阅读文件,这是我的主要问题。如果有人能提供一个如何使用JSON的例子,我将不胜感激。感谢您的快速回复
function httpGet(url, callback) {
    // this function gets the contents of the URL. Once the
    // content is present it runs the callback function.
    var xmlhttp=new XMLHttpRequest();
    xmlhttp.onreadystatechange=function() {
        if (xmlhttp.readyState==4 && xmlhttp.status==200) {
            callback(xmlhttp.responseText);
        }
    }
    xmlhttp.open("GET", url, false );
    xmlhttp.send();    
}

httpGet("url-of-your-file", function(textFile){
    // this calls the httpGet function with the URL of your text
    // file. It then runs a function that turns the file into an
    // array.
    var array = textFile.slice(1, -1).split("],[");
    console.log(array);
});