我试图创建一个网站,可以下载并通过启动其索引文件在本地运行。

所有文件都是本地的,没有在线使用资源。

当我尝试使用jQuery的AJAXSLT插件来处理带有XSL模板的XML文件(在子目录中)时,我收到以下错误:

XMLHttpRequest无法加载文件:///C:/path/到/XSL%20Website/data/home.xml。Access-Control-Allow-Origin不允许原点为空。

XMLHttpRequest无法加载文件:///C:/path/到/XSL%20Website/assets/ XSL /main.xsl。Access-Control-Allow-Origin不允许原点为空。

提出请求的索引文件是file:///C:/path/to/XSL%20Website/index.html,而使用的JavaScript文件存储在file:///C:/path/to/XSL%20Website/assets/js/。

我该如何解决这个问题?


当前回答

如果您只需要在本地访问文件,那么您可以包含文件的确切路径,而不是使用

../images/img.jpg

use

C:/Users/username/directoryToImg/img.jpg

CORS发生的原因是因为你试图在一个网页中遍历到另一个目录,通过包括直接路径,你不是在改变目录,你是从一个直接位置拉。

其他回答

打开浏览器绕过这个限制:打开-a "/Applications/谷歌chrome。app/Contents/MacOS/谷歌Chrome"——args——allow-file-access-from-files。

源自Josh Lee的评论,但我需要指定谷歌Chrome的完整路径,以避免谷歌Chrome从我的Windows分区打开(在Parallels中)。

下面是一个applescript,它将开启——allow-file-access-from-files开关,用于OSX/Chrome开发者:

set chromePath to POSIX path of "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"    
set switch to " --allow-file-access-from-files"
do shell script (quoted form of chromePath) & switch & " > /dev/null 2>&1 &"

您可以尝试输入'Access-Control-Allow-Origin':'*'作为响应。writeHead({[这]})。

使用javascript的FileReader函数来打开本地文件,比如:

<input type="file" name="filename" id="filename">
<script>
$("#filename").change(function (e) {
  if (e.target.files != undefined) {
    var reader = new FileReader();
    reader.onload = function (e) {
        // Get all the contents in the file
        var data = e.target.result; 
        // other stuffss................            
    };
    reader.readAsText(e.target.files.item(0));
  }
});
</script>

现在单击选择文件按钮,浏览到文件文件:///C:/path/to/XSL%20Website/data/home.xml

对于运行本地web服务器不是一个选项的实例,你可以允许Chrome通过浏览器开关访问file:// files。经过一番挖掘,我发现了这个讨论,其中提到了一个浏览器开关在开放的帖子。运行你的Chrome实例:

chrome.exe --allow-file-access-from-files

对于开发环境来说,这可能是可以接受的,但仅此而已。你肯定不希望它一直开着。这似乎仍然是一个悬而未决的问题(截至2011年1月)。

参见:在Chrome中使用本地文件的jQuery getJSON的问题