1

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";
}

1 Answers1

0

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.

Community
  • 1
  • 1
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875