I have a file that contains a list of data, an "array php", and what I want is to read it with JavaScript to convert it into a JavaScript array.
I have a file that contains a list of data, an "array php", and what I want is to read it with JavaScript to convert it into a JavaScript array.
You have two options:
The option to choose depends on your design. If the file will be shared by all clients, then it is convenient to use AJAX. If the files can be customized by the clients themselves and then loaded, then it is better to use the File API.
File API
This part of the API has quite good compatibility (IE10 +); what you have to do is take the File object that represents the selected file and then read it as text using FileReader#readAsText
.
function readFile(files) {
let reader = new FileReader();
let file = files[0];
reader.onloadend = function () {
let output = document.getElementById('output');
output.textContent = this.result;
}
reader.readAsText(file, 'ISO-8859-4');
}
@import url('https://fonts.googleapis.com/css?family=Open+Sans');
#output {
border: 3px dashed #777;
border-radius: 4px;
display: block;
line-height: 20px;
margin-top: 20px;
padding: 15px;
}
input[type="file"] {
display: none;
}
input[type="file"] + label {
background-color: #8e44ad;
border-radius: 3px;
color: #fff;
display: inline-block;
font-family: 'Open Sans';
font-size: 14px;
height: 35px;
line-height: 35px;
text-align: center;
padding: 0 15px;
}
h3 {
color: #555;
font-family: 'Open Sans';
}
<input type="file" id="file" onchange="readFile(this.files)">
<label for="file">Select file</label>
<h3>Contenido</h3>
<code id="output">No content</code>
AJAX
This form is compatible with every browser. You only need to make a request to that file and its content will be obtained.
function readFile () {
let xhr = new XMLHttpRequest();
xhr.open('GET', 'https://raw.githubusercontent.com/Agile-Android-Software-Development/agile-android-software-development-book/master/en/version.txt');
xhr.setRequestHeader('Accept', 'text/plain');
xhr.onload = function () {
if (xhr.status === 200 && xhr.readyState === 4) {
let output = document.getElementById('output');
output.textContent = this.responseText;
}
}
xhr.send();
}
@import url('https://fonts.googleapis.com/css?family=Open+Sans');
h3 {
color: #555;
display: inline-block;
font-family: 'Open Sans';
}
button {
background-color: #8e44ad;
border: none;
border-radius: 3px;
color: #fff;
cursor: pointer;
display: inline-block;
font-family: 'Open Sans';
font-size: 14px;
height: 30px;
line-height: 30px;
text-align: center;
padding: 0 15px;
}
#output {
border: 3px dashed #777;
border-radius: 4px;
display: block;
line-height: 20px;
margin-top: 20px;
padding: 15px;
}
<h3>Contenido</h3>
<button onclick="readFile()">Read file</button>
<code id="output">No content</code>