0

I need to load a text file in js, the text file is in the same dir as the .js file.

I found this code

var file = new XMLHttpRequest()
file.open("GET", "file.txt", true)
file.send()

file.onreadystatechange = function () {
    if (file.readyState == 4 && file.status == 200) {
        console.log(file.responseText)
    }
}

But that doesn't work if I open my site locally ("file:///C:/site.html")

How can I load a text if it is run locally? (Without using JQuery)

EDIT

I do not want to use JQuery but these are some questions with using JQuery.

"Ajax in Jquery does not work from local file" or "Jquery load() only working in firefox?"

Lupus Ossorum
  • 450
  • 3
  • 16
  • 1
    Run your script on a local server (like AMPPS, WAMP, MAMP, etc.) instead of from a directory. The reason is because most browsers prevent remotely downloaded HTML files that, when opened, have access to local files. – Terry Dec 29 '16 at 02:00

1 Answers1

1

The security policies of web browsers disallow getting file resources. You can, however, use JSONP to circumvent this:

var tag = document.createElement("script");
tag.src = 'filename.txt';

document.getElementsByTagName("head")[0].appendChild(tag);
function callback (data) {

}

You'll need filename.txt to look something like this:

callback('<text-file-content>')
noɥʇʎԀʎzɐɹƆ
  • 9,967
  • 2
  • 50
  • 67