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 is working fine in firefox at least.
The problem I was facing is, that I got an XML object in stead of a plain text string. Reading an xml-file from my local drive works fine (same directory as the html), so I do not see why reading a text file would be an issue.
I figured that I need to tell jquery to pass a string in stead of an XML object. Which is what I did, and it finally worked:
Note the addition of '"text"' at the end. This tells jquery to pass the contents of 'file.txt' as a string in stead of an XML object. The alert box will show the contents of the text file. If you remove the '"text"' at the end, the alert box will say 'XML object'.
You can't do this without the WEB SERVER!!! Chrome sends XMLHttpRequest to the system that looks something like this
And the operating system is not listening on port 80 to receive this! And even if it is, it must implement HTTP protocol to communicate with the browser...
To get this working, you must have WEB SERVER installed on your system, that will listen on port 80 and make your files available through a HTTP connection, thus making your code runnable.