Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

    }
like image 608
user1788736 Avatar asked Feb 03 '26 01:02

user1788736


2 Answers

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.

like image 133
iConnor Avatar answered Feb 05 '26 18:02

iConnor


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;
});
like image 37
Shiva Avatar answered Feb 05 '26 18:02

Shiva



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!