0

我是 javascript 新手,并且有一些数据存储在我想在我的网页上使用的 txt 文件中。

但是,当我发送 XmlHttpRequest 以获取文本文件时,firefox 在我试图读入的 .txt 的第一行引发语法错误。

这是我的代码:

    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); 

以下是来自 Firefox 的错误消息:

语法错误:“文件:\\myinfo.txt”行:1

然后在这里它有这一行的文字

我认为这可能意味着我不允许访问本地文件,这是 Firefox 让我知道这一点的方式。

有没有人对此错误有任何经验或知道它的含义?

4

1 回答 1

2

反斜杠字符在字符串中具有特殊含义。它表示下一个字符在某些方面是特殊的,例如,您可以通过使用反斜杠在字符串中包含引号来转义它:

'It\'s a string'

为了包含一个文字反斜杠,你把它放了两次:

'This is one backslash \\ character'

所以,在你的例子中,你有\\\m. 前两个斜杠变成一个斜杠,并且\m未被识别为有效的转义序列,因此您会收到错误消息。

更改您的 URL 以使用正斜杠(它没有这种特殊含义,并且无论如何都是在 URL 中使用的正确斜杠类型),或者加倍您的反斜杠:

"file:///myinfo.txt"
"file:\\\\\\myinfo.txt"

另外,请注意这个 URL 实际上并不指向任何东西,它应该是这样的:

"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/.

于 2011-06-22T15:52:59.467 回答