ProgrammingFreak
ProgrammingFreak

Reputation: 35

Reading a txt file from Server, writing it to website

Here's my problem.

1) I'm wanting to create a txt file (or possibly a html file) to hold a paragraph of information to be written onto a when a user clicks a word. It's part of a game I am working on.

If you go to www.w3schools.com and go to their "try it" editor they have...

<!DOCTYPE html>
<html>
<head>
<script>
function loadXMLDoc()
{
var xmlhttp = XMLHttpRequest();
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
p = document.createElement("p");
p.innerHTML=xmlhttp.responseText;
document.getElementById("story").appendChild(p);
}
}
xmlhttp.open("GET","ajax_info.txt",true);
xmlhttp.send();
}
</script>
</head>
<body>

<div id="story"><h2>Let AJAX <i onclick=loadXMLDoc()>change</i> this text</h2></div>

</body>
</html>

This is exactly what I want my program to do (not the actual words of course) but I'm running html with an external .js sheet. Should I store my ajax somewhere else? Or, should my .txt file look different than just a bunch of words in it? I'm completely confused.

The fun part will be once this actually starts working, I'm going to have to implement an "onclick" event with italics inside of the txt file.

If there is a better way to do this then appendChild(p.innerHTML("lfjhdfh")) and AJAX please let me know asap. I have a total of 11 weeks to get this thing working for a school project LOL.

Upvotes: 0

Views: 2045

Answers (1)

Tom
Tom

Reputation: 4592

Try this, it just appends the text to the HTML of the body element:

function getFileFromServer(url, doneCallback) {
    var xhr;

    xhr = new XMLHttpRequest();
    xhr.onreadystatechange = handleStateChange();
    xhr.open("GET", url, true);
    xhr.send();

    function handleStateChange() {
        if (xhr.readyState === 4) {
            doneCallback(xhr.status == 200 ? xhr.responseText : null);
        }
    }
}

function ajax() {
    getFileFromServer("Test.txt", function (text) {
        if (text === null) {
            // An error occurred
        } else {
            document.body.innerHTML += test;
        }
    });

}

Upvotes: 2

Related Questions