Last active
February 21, 2020 21:16
-
-
Save asjain/6107fb6ecfde7b4d2cf884f4677c3c6e to your computer and use it in GitHub Desktop.
read file in html
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html> | |
<style> | |
table, td { | |
border: 1px solid black; | |
width:1000px; | |
text-align: center; | |
} | |
</style> | |
<body> | |
<h2 text-align="center">Learn JS</h2> | |
<h3>Welcome to broken tutorials. We will learn to read a text file and dynamically create tables from it</h3> | |
<div> | |
<p>The lines in the text file will make the rows and we will form the columns</p> | |
<table id="mainTable"> | |
<tr> | |
<th>Animals</th> | |
<th>All</th> | |
<th>Most Viewed</th> | |
</tr> | |
</table> | |
<script> | |
var base_url = "https://imgur.com/r/" | |
var tail_url_top = "/top" | |
function display_file() // defining the file reading function. it also creates tables for us | |
{ | |
var httpRequest = new XMLHttpRequest(); | |
var table = document.getElementById("mainTable"); | |
httpRequest.open("GET", "my.txt", true); // specify the file name, in our case, it is in the same folder as this html page | |
httpRequest.send(null); | |
httpRequest.onreadystatechange = function() | |
{ | |
if(this.readyState == 4 && this.status == 200) | |
{ | |
var fileContent = this.responseText; | |
var fileArray = fileContent.split('\n'); | |
var n = fileArray.length; | |
for (var i=0; i<n-1 ; i++) | |
{ | |
var animal = fileArray[i]; | |
animal = animal.replace(/\s+/g, "") // removing whitespaces | |
var url_all = base_url + animal // this one does not need a tail url | |
var url_top = base_url + animal + tail_url_top | |
var row = table.insertRow(-1); // insert a row first, which will have cells | |
var cell1 = row.insertCell(0); // creating empty cells of this row | |
var cell2 = row.insertCell(1); | |
var cell3 = row.insertCell(2); | |
cell1.innerHTML = '<td>'+animal+'</td>'; // content for the first cell of this row | |
cell2.innerHTML = '<td><a href="'+url_all+'">All</a></td>'; // second cell | |
cell3.innerHTML = '<td><a href="'+url_top+'">Most Viewed</a></td>'; // third cell | |
} | |
} | |
} | |
} | |
</script> | |
</div> | |
<body onload="display_file()"> | |
<p id="p1"></p> | |
</body> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment