Simple Way to Display Data in a .Txt File on a Webpage

simple way to display data in a .txt file on a webpage?

Easy way:

  • Rename missingmen.txt to missingmen.html.
  • Add a single line to the top of missingmen.html:

    <link href="txtstyle.css" rel="stylesheet" type="text/css" />
  • Create a file called txtstyle.css, and add to it a line like this:

    html, body {font-family:Helvetica, Arial, sans-serif}

Display text file in HTML

You can just use an <iframe>:

<iframe src="http://stackoverflow.com/reputation"></iframe>

How do I include the contents of a text file into my website?

Just don't read files in js in a web browser.
You can create an API with node.js and then make an http request to get this data.

Once you created the server, just do like that:

const fs = require('fs');var content;// First I want to read the filefs.readFile('./Index.html', function read(err, data) {    if (err) {        throw err;    }    content = data;
// Invoke the next step here however you like console.log(content); // Put all of the code here (not the best solution) processFile(); // Or put the next step in a function and invoke it});
function processFile() { console.log(content);}

Show a txt file on a webpage which updates every second

My answer uses PHP and Ajax though changing to ASP or any other language wont be hard.

In the head

    <script type="text/javascript">

function Ajax()
{
var
$http,
$self = arguments.callee;

if (window.XMLHttpRequest) {
$http = new XMLHttpRequest();
} else if (window.ActiveXObject) {
try {
$http = new ActiveXObject('Msxml2.XMLHTTP');
} catch(e) {
$http = new ActiveXObject('Microsoft.XMLHTTP');
}
}

if ($http) {
$http.onreadystatechange = function()
{
if (/4|^complete$/.test($http.readyState)) {
document.getElementById('ReloadThis').innerHTML = $http.responseText;
setTimeout(function(){$self();}, 1000);
}
};
$http.open('GET', 'loadtxt.php' + '?' + new Date().getTime(), true);
$http.send(null);
}

}

</script>



In the Body

    <script type="text/javascript">
setTimeout(function() {Ajax();}, 1000);
</script>
<div id="ReloadThis">Default text</div>

</body>

Now using loadtxt.php read the values of the text file

    <?php
$file = "error.txt";
$f = fopen($file, "r");
while ( $line = fgets($f, 1000) ) {
print $line;
}
?>

Populate local text file data to web page using html

you could have it done with AJAX request, like this:

<div id="mydiv"></div>
<script>
window.load = loadDoc();
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("mydiv").innerHTML =
this.responseText;
}
};
xhttp.open("GET", "text.txt", true);
xhttp.send();
}
</script>

Note: You may run your test with a webserver (I tested this with XAMPP). Make sure your text file lives on same directory as your html file.



Related Topics



Leave a reply



Submit