简体   繁体   English

javascript - 读取外部本地.txt文件以将数据加载到数组中

[英]javascript - reading in an external local .txt file to load data into an array

I currently have javascript code (please see below) that searches an array for a month/day combination, and if it is found, assigns the name of a .jpg file (which is used for the background image of a page). 我目前有javascript代码(请参见下文)搜索数组中的月/日组合,如果找到,则指定.jpg文件的名称(用于页面的背景图像)。 Instead of hard-coding all of the data in the array, I'd like to be able to create an external .txt file with month/day codes and associated image file names, that could be read and loaded into the array. 我希望能够创建一个带有月/日代码和相关图像文件名的外部.txt文件,而不是对数组中的所有数据进行硬编码,这些文件可以读取并加载到数组中。 Thanks for your help! 谢谢你的帮助!

var ourdates = ['0000','0118','0215','0530','0614','0704','0911','1111','1207']

if (ourdates.indexOf(monthday) != -1)

{
ourimage = "flag";
}

If you mean loading it from your server, that's a classic use-case for ajax, frequently combined with JSON: 如果您的意思是从服务器加载它,这是ajax的经典用例,经常与JSON结合使用:

 var ourdates = null; var xhr = new XMLHttpRequest(); xhr.open("GET", "/path/to/your/data"); xhr.onreadystatechange = function() { if (xhr.readyState == 4 && xhr.status == 200) { ourdates = JSON.parse(xhr.responseText); // call something that uses `ourdates` } }; xhr.send(null) 

If you mean from the user's computer, my answer here shows how to do that with the File API. 如果您的意思是来自用户的计算机, 我的答案显示了如何使用File API执行此操作。 Doing that requires an <input type="file"> input (or drag-and-drop event) that the user uses to grant access to the file to your script. 这样做需要一个<input type="file">输入(或拖放事件),用户可以使用该输入将文件的访问权授予脚本。 You can't read a file from their machine without them specifically giving you access to the file. 如果没有专门授予您访问该文件的文件,则无法从其计算机中读取文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM