How to pass the contents of a.txt file to a JS array?

Asked

Viewed 1,254 times

1

I have this problem, I would like to know what you suggest I research to solve it. I tried using . split, Filereader. It can be in Js, Jquery or Ajax. Any suggestion is welcome. I researched on the subject but found nothing concrete on this my problem. I appreciate all your help.

  • 1

    But what is the content of the txt file?

  • First Voce needs to load the txt file, then Voce uses ajax, from ai Voce will already have the contents of txt as string, then just manipulate it. As there is no more information it is difficult to give examples. if you can put content or txt snippet it helps enough

  • jbueno, only numbers.

  • @Neuberoliveira, the contents are only numbers, can be 1 in each line or separated by comma.

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
  • Thanks for the help @Neuber Oliveira, I will try to follow this line of reasoning. As for the.txt file you used was local?

  • Yes it was local, but via ajax as this loads from virtually any url

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>
  • Look in the Console if you are finding the file numeros.txt

  • I tried to type the numbers in string form and still Alert does not run. I did var res = "1,2,3,4,5,6,7,8"

  • @Snail open your console (F12 on Chrome and go to the console tab) and check the file numeros.txtis being found

  • You’re right, he’s not being found. The following error appears: Xmlhttprequest cannot load file://C:/Users/Documents/Project%20from%20Psearch/Search project/Files%20Javascript/numbers.txt. Cross origin requests are only supported for Protocol schemes: http, data, Chrome, Chrome-Extension, https, Chrome-Extension-Resource. Any suggestions on how to resolve?

  • Cross Origin? Which folder is your HTML in? (has MANY spaces in the names of your folders (the '%20'), if possible remove them)

  • I deleted the spaces, the error continues Xmlhttprequest cannot load file://C:/Users/Cassi/Documents/Arqjs/numeros.txt. Cross origin requests are only supported for Protocol schemes: http, data, Chrome, Chrome-Extension, https, Chrome-Extension-Resource.

  • @Caraujo Your HTML is in this folder: "C:/Users/Cassi/Documents/Arqjs/"?

  • is. Along with txt file

  • @Snail Are you running this inside the WAMP? Or just opening the html file? Because if you just play HTML in the browser, it will never work, precisely because of this Cross error, but inside a server the solution I built for you works.

  • thanks for the help, it was running right in the browser, so the error. Now running on Xampp worked right.

Show 5 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.