Set a text file on the server to be read whenever you run .html (with embedded Javascript language)

1

I need the browser to return me pre-registered information of people and their addresses, where each has two houses on the same street.

For this, I simulated a server in my pc folder, and so I created a data.txt file in the same directory as a .html file.

In the data.txt file I wrote the following data to be used by the system as a database:

[item] | 1 | Danilo | 13057423 | 1 | 200 | [item] | 2 | Denise | 13059778 | 200 | 500 | [item] | 3 | Guilherme | 13052445 | 500 | 1000 |

In this data, I am trying to get the system to recognize that Danilo has two homes in CEP 13057423, number 1 and 200. And Denise in the same way, and so on.

So, I researched how to get the system to read this information and return the data to me automatically, but I only found a way where I would have to upload the file every time I needed the data, see the following code:

<html>
<body>
	<head>
		<title>Listando itens de arquivo TXT |</title>
	</head>
 <style type="text/css">
 	#lista{
 		width:50%;
 		border: 1px solid black;
 	 	}
 </style> 
 
<table>
	<tr>
		<div>Escolha um arquivo de texto para carregar:</div>
		<div><input type="file" id="fileToLoad"></div>
		<div><button onClick="loadFileAsText()">Carregar o arquivo selecionado</button><div>
	</tr>
</table>
<table id="lista" border="1">
	<tr>
		<div>Nome</div>
		<div>CEP</div>
		<div>número da casa</div>
		<div>número da casa 2</div>
	</tr>
</table>
<script type='text/javascript'>
function loadFileAsText()
{
	var fileToLoad = document.getElementById("fileToLoad").files[0];

	var fileReader = new FileReader();
	fileReader.onload = function(fileLoadedEvent) 
	{
		var textFromFileLoaded = fileLoadedEvent.target.result;
		var texto = textFromFileLoaded;
		listar(texto);
	};
	fileReader.readAsText(fileToLoad, "UTF-8");
}
function listar(texto){
	var quantidade = document.getElementById("lista").rows.length;
	if (quantidade>1){
		for(var cont=1;cont<=quantidade;cont++){
			document.getElementById("lista").deleteRow(cont);
		}
	}
	var itens = texto.split('[item]');
	for(var i=1;i<itens.length;i++){
		var valores = itens[i].split("|");
		document.getElementById("lista").innerHTML +='<tr><div>'+valores[1]+'</div><div>'+valores[2]+'</div><div>'+valores[3]+'</div><div>'+valores[4]+'</div></tr>';
	}
}
</script>
</body>
</html>

Now, my goal is to make the system load the file automatically, without having to "upload" it every time I need the system to return the information in the browser.

>

I researched a lot, and I was able to find some information on how to do this. I made changes to the code and it looks like this:

<html>
<body>
	<head>
		<title>Listando itens de arquivo TXT |</title>
	</head>
 <style type="text/css">
 	#lista{
 		width:50%;
 		border: 1px solid black;
 	 	}
 </style> 
 
<table>
	<tr>
		<iframe id="fileToLoad" src="dados.txt" style="display: none;"></iframe>
		<div><button onClick="loadFileAsText()">Mostrar as informações de Nome, CEP, número da casa 1 e 2</button><div>
	</tr>
</table>
<table id="lista" border="1">
	<tr>
		<div>Nome</div>
		<div>CEP</div>
		<div>número da casa</div>
		<div>número da casa 2</div>
	</tr>
</table>
<script type='text/javascript'>
function loadFileAsText()
{
	var fileToLoad = document.getElementById("fileToLoad").files[0];

	var fileReader = new FileReader();
	fileReader.onload = function(fileLoadedEvent) 
	{
		var textFromFileLoaded = fileLoadedEvent.target.result;
		var texto = textFromFileLoaded;
		listar(texto);
	};
	fileReader.readAsText(fileToLoad, "UTF-8");
}
function listar(texto){
	var quantidade = document.getElementById("lista").rows.length;
	if (quantidade>1){
		for(var cont=1;cont<=quantidade;cont++){
			document.getElementById("lista").deleteRow(cont);
		}
	}
	var itens = texto.split('[item]');
	for(var i=1;i<itens.length;i++){
		var valores = itens[i].split("|");
		document.getElementById("lista").innerHTML +='<tr><div>'+valores[1]+'</div><div>'+valores[2]+'</div><div>'+valores[3]+'</div><div>'+valores[4]+'</div></tr>';
	}
}
</script>
</body>
</html>

Notice that Chrome has a security system that does not allow the reading of files in physical directory, so I used Firefox for the simulation tests.

I can not in any way get the browser to display the information without my having to upload the file (this was before I made any modifications to the code).

Can anyone help me or direct me to some link that will help me accomplish this relatively simple task? I have tried debugging in all the ways I know, inspecting chrome, checking for console errors, and what it shows is always the same error message, which you can see by clicking on "run" right up here.

I would love to be able to do this using Javascript (without using jQuery / Ajax).

Any suggestions on how to improve my question and my research is always welcome.

Thank you very much.

    
asked by anonymous 18.07.2017 / 06:03

1 answer

2

You can store the information in a json file on the "static server" and query using Fetch API which already returns a parsed result of json for a javascript object (if there is a file with valid syntax)

Example:

// arquivo json no servidor (test.json)
{
    "fulano": "Chico",
    "Fulana": "Aninha"
}

// buscando os dados
fetch('./test.json').then((response)=>{
    if (response.ok) {
        return response.json(); // aqui retorna parseado para a promise subsequente
    }
    throw new Error('Resposta Invalida'); // aqui lança para o "catch"
}).then((dados)=>{
    // aqui dados já é um objeto javascript de test.json
    console.log(dados.fulano); // imprime: Chico
}).catch((error)=>{
    // trate a exceção ou erro aqui
});

As you can see, it is a basic example of how you can structure a static bank in json better than plain text since fetch already converts to object you can go through arrays and do all checks normally

As fetch works with Promise in case there is always an error will fall in catch .

(edition) a more practical example:

data.json

[
    {
        "name": "Danilo",
        "cep": "13057423",
        "casas": [
           "1",
           "200"
        ]
    },
    {
        "name": "Denise",
        "cep": "13059778",
        "casas": [
           "200",
           "500"
        ]
    },
    {
        "name": "Guilherme",
        "cep": "13052445",
        "casas": [
           "500",
           "1000"
        ]
    }
]

index.html

<body>
    <div id="show-users"></div>

    <button id="sur">Mostrar usuários registrados</button>


    <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script><scripttype="text/javascript">
        // variavel que irá receber a database
        var data;

        // button event
        $('#sur').on('click', function(event){
           event.preventDefault();
           // percorrer a database
           for (let i = 0; i < data.length; i++) {
                // mostrar usuários por nome
                $('#show-users').append('<span>'+data[i].name+'</span>';
           }
        });


        fetch('./dados.json').then((response)=>{
            if (response.ok) {
                return response.json();
            }
        }).then((dados)=>{
            /**
             * manipule o array de dados aqui ou sete uma variável pré-definida
            for (let i = 0; i < dados.length; i++) {
                 // sua lógica aqui
            }
            */
             data = dados; // atribuir para a variável "data"
        }).catch((e)=>{
            console.log(e);
        });
    </script>
</body>
    
18.07.2017 / 12:39