0

I am using JavaScript locally on a Windows computer. In the folder that I put this .jsp file, I have a file named text.txt. I want this .jsp file to display the content of the file. It is as if my function is never invoked. I use a web browser to test the script. I see "JavaScript locally on Windows" as my header shows. What should I do to get my function to work? I get no error message. I searched the internet. I based my code off of this link.

<HTML>
<HEAD>
<TITLE> Javascript locally on Windows </TITLE>
</HEAD>
<BODY>
<h2>JavaScript locally on Windows</h2>

<script language="Javascript">


function readContentOfFile(file)
{
    var inputFile = new XMLHttpRequest();
    inputFile.open("GET", file, false);
    inputFile.onreadystatechange = function ()
    {
        if(inputFile.readyState === 4)
        {
            if(inputFile.status === 200 || inputFile.status == 0)
            {
                var contentText = inputFile.responseText;
                alert(contentText);
            }
        }
    }
    inputFile.send(null);
}


readContentOfFile(text.txt)

</script>


</BODY>
</HTML>
Community
  • 1
  • 1
Ahmed
  • 1

1 Answers1

2

The error is when you pass the file name as parameter to the function.

Watch for:

inputFile.open("GET", file, false);

open is a method of the XMLHttpRequest object that expects the second parameter as a string. Because you define this variable on the function parameter here:

function readContentOfFile(file)

You should pass the parameter as a string wrapping it in quotes:

readContentOfFile("text.txt")