[英]Read txt file and put into javascript array
我想知道如何读取 txt 文件并将其内容放入 javascript 数组中。
我的 txt 文件看起来像这样。 [皮肤1]、[皮肤2]、[皮肤3]等...
我只是希望从 txt 文件中获取数组内容,而不是将数组写入实际的 html 文件。
我对javascript相当陌生,不明白如何做到这一点。
Ps 我的 html 和 txt 文件将在同一台服务器上。 如果这有所作为。
我真的很感激示例代码,提前致谢。
如评论中所述,如果文本文件以 JSON 编码,则会更有效地实现。 但是,在不知道文本文件是如何生成的情况下,我无法推荐一种将其生成为 JSON 的方法,因此这里是您解析当前文件的方法。
假设您正在前端读取文本文件的内容,您将使用XMLHttpRequest
异步获取文本文件的内容。 收到文件内容后,您会将其转换为数组。 在您提供的文本文件格式为[Skin1],[skin2],[skin3]
的特定情况下,您将删除第一个[
和最后一个]
,然后按描述],[
分割。
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);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.