简体   繁体   中英

getting data from file.txt and returning it with an array

i have file.txt

apple     <--line 1 
banana    <--line 2

and this is my script

url = 'file.txt';
homelists = [];

$.get(url, function(data) {

  var lines = data.split("\n");    <--i want to split it by line

  $.each(lines, function(n ,urlRecord) {
    homelists.push(urlRecord);  <--add it to my homelists array
  });

});

console.log(homelists);   <-- returns array
console.log(homelists[0]);  <--undefined

my problem is i cant get the inside value of homelists how can i get homelists[0] or homelists[1]..(javascript or jquery(preferrable))

Javascript/Jquery ajax is an Async call meaning the code $.get and console.log on your example will be executed parallelly (immediate or the same times), so to parse the result of your file.txt, you need to do it inside the function (which will be executed after ajax called is done).

url = 'file.txt';
homelists = [];
$.get(url, function(data) {
  var lines = data.split("\n");  
  $.each(lines, function(n ,urlRecord) {
    homelists.push(urlRecord); 
  });
    console.log(homelists);  
    console.log(homelists[0]); 
});

I know this is too simple answer and may sound stupid to others but i have an idea. why not store in the session the $.get data

url = 'file.txt';
$.get(url, function(data) {
    localStorage['homelists'] = data;
});

then assign a variable to that session

homelists = localStorage['homelists'];

then make the session = null

localStorage['homelists'] = null

when you do console.log outside

console.log(homelists);      <-returns string which you can manipulate to turn it into array
console.log(localStorage['homelists']);  <-returns null

I dont know yet what could be the bad side/effect of this with my project.. any idea?

Since you are using jQuery, It would be better if you use AJAX . !

 const ImportData = function(file){ let arrayData = undefined; $.ajax({ url: file, type: 'GET', error: (err) => { throw new Error(err) }, success: ( data ) => { arrayData = MakeArray( data ); //Do whatever you want here console.log( arrayData ); } }); } const MakeArray = function(plaintext){ const array = []; plaintext.split('\n').forEach( (line) => { line = line.trim(); array.push( line ); } ); return array; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script> const file = "https://www.w3.org/TR/PNG/iso_8859-1.txt"; document.addEventListener('DOMContentLoaded', function(){ ImportData( file ); }); </script>

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