简体   繁体   中英

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). 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. 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:

 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. 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. You can't read a file from their machine without them specifically giving you access to the file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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