How to pass the contents of a .txt file to a vector in JS? [closed]

1

I'm having this problem, I'd like to know what you suggest me to search for to solve it. I tried to use the .split, FileReader. It can be in Js, Jquery or Ajax. Any suggestions are welcome. I researched the subject but found nothing concrete about my problem. Thank you for your help.

    
asked by anonymous 08.02.2017 / 14:03

2 answers

1

This resolves, unless your .txt file is too chaotic.

var numsList = [];
$.ajax( 'arquivo.txt', {
    dataType: 'text',
    success: function(response){
        //response é o conteudo do arquivo.txt
        var lines = response.split('\n'); //quebra o arquivo em linhas, 
        for(var i in lines){
            var row = lines[i];
            var nums = row.split(','); //quebra a linha em valores separdos por virgula
            for(var j in nums){
                var num = parseInt(nums[j]); //converte o valor para int
                if( !isNaN(num) ) //basicamente verifica se é um numero
                    numsList.push(num); //adiciona o item no array
            }
        }

        console.log(numsList);
    }
});

I tested the code in a txt file with the following content

1,2,3,4,5,6,7,8,9,10,

11,12,13,14,15,16,17,18,19,20,
21, 22, 23, 24, 25,26, 27, 28, 29, 30
    
08.02.2017 / 14:37
0

Very simply:

<script>
function loadDoc() {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      var res = this.responseText;
      alert(res); //  A Variável res terá o conteúdo.
    }
  };
  xhttp.open("GET", "seu_arquivo_txt.txt", true);
  xhttp.send();
}
</script>
    
08.02.2017 / 14:16