Read text file and display in web page
10,245
Solution 1
<!DOCTYPE html>
<html>
<head>
<script src="jquery.min.js"></script>
</head>
<Body>
<p><center>Current Track: <span id="trackinfo">No track information available at this time</span></p></center>
<script>
function radioTitle() {
var url = 'http://XXX.no-ip.org:8000/tracktitle.txt';
$.ajax({
type: 'GET',
url: url,
dataType: 'text',
success: function(data) {
$("#trackinfo").html(data)
},
error: function(e) {
console.log(e.message);
}
});
}
$(document).ready(function(){
setTimeout(function(){radioTitle();}, 2000);
setInterval(function(){radioTitle();}, 15000);
});
</script>
</body>
</head>
</html>
Solution 2
var tid = setInterval(mycode, 2000);
function mycode() {
// do some stuff...
// no need to recall the function (it's an interval, it'll loop forever)
readTextFile("your file path");
}
function abortTimer() { // to be called when you want to stop the timer
clearInterval(tid);
}
function readTextFile(file)
{
var rawFile = new XMLHttpRequest();
rawFile.open("GET", file, false);
rawFile.onreadystatechange = function ()
{
if(rawFile.readyState === 4)
{
if(rawFile.status === 200 || rawFile.status == 0)
{
var allText = rawFile.responseText;
alert(allText);
}
}
}
rawFile.send(null);
}
Related videos on Youtube
Author by
Colin Davis
Updated on September 15, 2022Comments
-
Colin Davis over 1 year
I am seeking some help. I am very new to programming and I’m working on a new project.
The objective is to display the contents of a plain text file in a web page.
The text file (named title.txt) and has a single line of text The text file is located on my server The text content changes every three minutes or so.
I wish to read this file and display its content in a web page The web browser is to automatically re-read the file every three minutes or so.
I have looked at a number of websites to achieve this, however i am confused by the options available. I read that Jquery/ajax can perform this task.
Can anyone help me by providing some example code.
Many thanks Colin
-
Colin Davis over 8 yearsI managed to achieve my objective with the above code. Thanks for your help.