I am trying to read a text file using jquery, like this:
// LOAD file and split line by line and append divs
$.get('myFile.txt', function(data) {
var lines = data.split("\n");
$.each(lines, function(n, elem) {
$('#myContainer').append('<div>' + elem + '</div>');
});
});
In chrome, I am getting:
XMLHttpRequest cannot load file:///C:/myPath/myFile.txt. Origin null is not allowed by Access-Control-Allow-Origin.
Firefox shows no error but the code is not executed (I have breakpoints in firebug and the anonymous function never runs).
Any help appreciated!
EDIT:
had to:
- use the file full path
- launch chrome with "--allow-file-access-from-files"
now it's working OK!
This doesn't work and it shouldn't because it would be a giant security hole.
Have a look at the new File System API. It allows you to request access to a virtual, sandboxed filesystem governed by the browser. You will have to request your user to "upload" their file into the sandboxed filesystem once, but afterwards you can work with it very elegantly.
While this definitely is the future, it is still highly experimental and only works in Google Chrome as far as CanIUse knows.
As long as the file does not need to be dynamically generated, e.g., a simple text or html file, you can test it locally WITHOUT a web server - just use a relative path.
this one is working
A workaround for this I used was to include the data as a js file, that implements a function returning the raw data as a string:
html:
script.js:
See it in action here- http://plnkr.co/edit/EllyY7nsEjhLMIZ4clyv?p=preview The downside is you have to do some preprocessing on the file to support multilines (append each line in the string with
'\n\'
).specify the full path of the file url
You can't load a file from your local filesystem, like this, you need to put it on a a web server and load it from there. On the same site as you have the JavaScript loaded from.
EDIT: Looking at this thread, you can start chrome using option
--allow-file-access-from-files
, which would allow access to local files.