I have a text file structured like so...
Hello . world . . . . its me
I using the following code to read the txt file
<head>
<script type="text/javascript">
function readfileautomatically();
</script>
</head>
<body>
<body onload="readfileautomatically();">
<td id="foo"></td>
<script>
function readfileautomatically () {
var client = new XMLHttpRequest();
client.open('GET', '/foo.txt');
client.onreadystatechange = function() {
alert(client.responseText);
}
client.send();
}
</script>
</body>
Currently with the above I'm able to read the text file and alert the contents. I want to now expand my code and do this.
read foo.txt when page loads
assign line 3 world from the txt file id=line3
assign line 1 hello from the txt file id=line1
So that I can do this:
<td="line3"> world from txt file will be here </td>
<td="line1"> hello from txt file will be here </td>
Any help given would be greatly appreciated.
Let me know if you had any questions :)
<html>
<head>
</head>
<body onload="readfileautomatically();">
<div id="line1"></div>
<div id="line3"></div>
<script>
function readfileautomatically () {
var client = new XMLHttpRequest();
client.open('GET', '/foo.txt');
client.onreadystatechange = function()
{
if( client.responseText != '' )
{
var txt = client.responseText.split("\n");
document.getElementById("line1").innerHTML = txt[0];
document.getElementById("line3").innerHTML = txt[2];
}
}
client.send();
}
</script>
</body>
</html>
To split the file into lines, you can try the String#split
method, splitting by \n
characters (newlines). This would give you an array of lines.
For instance:
var text = client.responseText;
var lines = text.split("\n"); // create array of lines
document.getelementById("line3").innerHTML = lines[2]; // Arrays start at zero
document.getelementById("line1").innerHTML = lines[0];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With