JavaScript XMLHttpRequest syntax error
I am new to javascript and have some data stored in a txt file that I want to use on my webpage.
However when I send an XmlHttpRequest to get the text file firefox throws a syntax error on the first line of the .txt I am trying to read in.
Here is my开发者_开发问答 code:
var txtFile = new XMLHttpRequest();
txtFile.onreadystatechange = function() {
if (txtFile.readyState === 4) {
if (txtFile.status === 200) {
allText = txtFile.responseText;
lines = txtFile.responseText.split("\n");
}
}
}
txtFile.open("GET", "File:\\\myinfo.txt", true);
txtFile.send(null);
Here is what the error message from firefox reads:
syntax error: "File:\\myinfo.txt" Line:1
then down here it has the text that is on this line
I think it may mean that I'm not allowed to access a local file and this is firefox's way of letting me know this.
Does anyone have any experience with this error or know what it means?
The backslash character has special meaning in a string. It signifies that the next character is special in some way, for example you can include a quote inside a string by using the backslash to escape it:
'It\'s a string'
In order to include a literal backslash, you put it twice:
'This is one backslash \\ character'
So, in your example, you have \\\m
. The first two slashes become one slash, and the \m
is unrecognised as a valid escape sequence and so you get the error.
Change your URL to either use forward slashes (which don't have this special meaning and is the correct type of slash to use in a URL anyway), or double-up your backslashes:
"file:///myinfo.txt"
"file:\\\\\\myinfo.txt"
Also, note that this URL doesn't actually point to anything, it should be something like this:
"file:///C:/myinfo.txt"
Also, as pointed out above, XMLHttpRequest only works against the same domain as the page it's on is hosted, so if your page is on http://www.example.com/ you can only access resources on http://www.example.com/.
精彩评论