user1788736
user1788736

Reputation: 2845

how to load data from text file to javascript array?

i have an array called items=["apple","mango","cherry"];

i wonder how i can load the array data from text file instead of declaring it?the text file data is stored like this "apple","mango","cherry",...

furthermore, how to add to the end of this this text file an item for example add "orange" after "cherry"?

items=["apple","mango","cherry"];
    if (items.indexOf(myVariable2) == -1) {

     // not found, so output it
       t++;

    document.myform3.outputtext3.value +=myVariable2+"\n";

    }

Upvotes: 3

Views: 44604

Answers (3)

Shiva
Shiva

Reputation: 6887

Sorry, but I don't believe it's quite that simple. Browsers restrict access to local drives (and to server drives) for security reasons.

But one way to access the text file using jQuery would be

jQuery.get('http://localhost/foo.txt', function(data) {
    var myvar = data;
});

Upvotes: 4

user2587132
user2587132

Reputation:

 var file = event.target.file;
 var reader = new FileReader();
 var txt=reader.readAsText(file);
 var items=txt.split(",");

Upvotes: 0

iConnor
iConnor

Reputation: 20189

With jQuery you can do something like this

  $.get("textFile.txt", function(data) {
      var items = data.split(',');
  });

You may need something like this though

var items = data.replace(/"/g, '').split(',');

This is a start.

If this is a user input file then you may need to upload it before you work with it.

Upvotes: 5

Related Questions