I am new to javascript and am trying to read a file and display it contents on browser.
I have this code so far:
<script type="text/javascript">
var fname ;
if(navigator.appName.search('Microsoft')>-1) { fname = new ActiveXObject('MSXML2.XMLHTTP'); }
else { fname = new XMLHttpRequest(); }
function read(filename) {
fname.open('get', filename, true);
fname.onreadystatechange= steady;
fname.send(null);
}
function steady() {
if(fname.readyState==4) {
var el = document.getElementById('read_file');
el.innerHTML = fname.responseText;
}
}
</script>
But the output on I get is :
x y 5 90 25 30 45 50 65 55 85 25
Whereas the data is in format:
x y
5 90
25 30
45 50
65 55
85 25
Two questions:
1) How do i display it in the format as above
2) As of now, this happens when I click on a button.. is there any way I can automatically read from this given file rather than clicking on a button
SO this is how my html code looks like
<input type="button" value="load file" onclick="read('data.tsv')">
I want to get rid of this “onclick” and just read the file
THanks
To remove the button, just add the call to the end of your JavaScript:
There are a couple of ways to display the data as you find it in the file.
The first is to wrap it in an element that preserves white-space…
Or you could replace all the line breaks and tabs / spaces with HTML, for example a line break could be converted into a
<br>tag and a space could be replaced with a non-breaking space: .You could even split it by line-breaks and white-space in order to display it in a table, which would be the correct way of displaying the type of information you have.