最终产品:获取一个名为 theFile.txt 的文件,该文件与js和HTML文件一起保存并将其按行分解进入数组。
问题:在Firefox中正常运行但在Google Chrome中重现以下错误 :
XMLHttpRequest无法加载file:/// C:/ Users / (我的名字) /Documents/testFile/theFile.txt。收到无效回复。起源' null'因此不允许访问。
Javascript代码:
$('#infoStore').load('theFile.txt', function(result) {
text = result;
console.log('here: '+text);});
infoStore的HTML代码:
<div id="infoStore" hidden="true"></div>
提前感谢您的协助。我会在网上经常回答问题。
答案 0 :(得分:1)
这是因为Chrome使用file:
协议将所有来源视为彼此不同,因此Same Origin Policy开始发挥作用。这只是Chrome和其他一些浏览器之间的安全选择区别。
您基本上不能将ajax与通过file:
协议提供的本地文件一起使用。 (在Chrome中。)
您可以使用File API(this answer显示方式)读取文件,但当然这有限制(尤其是用户必须为您提供文件)通过<input type="file">
或拖放来阅读。
答案 1 :(得分:0)
这是因为Same-Origin-Policy。您应该从Web服务器加载该文件,而不是从本地目录加载。
答案 2 :(得分:0)
如果要访问chrome中的本地文件? 有时在Chrome中调试和测试javascript应用程序很酷,但是你想要读/写本地文件。示例:您正在寻找使用ajax并执行$ .getJSON('json / somefile.json')。 Chrome默认不允许这样做,并会抛出类似于
的错误Failed to load resource: No 'Access-Control-Allow-Origin'
header is present on the requested resource.
Origin 'null' is therefore not allowed access.
Or
XMLHttpRequest cannot load. No 'Access-Control-Allow-Origin'
header is present on the requested resource.
Origin 'null' is therefore not allowed access.
Chrome确实有一个启用此功能的开关,它很容易打开。您需要确保Chrome已完全关闭,并使用'-allow-file-access-from-files'标志运行chrome。即:
C:\Users\<user>\AppData\Local\Google\Chrome\Application>
chrome --allow-file-access-from-files
或者你应该能够跑:
%localappdata%\google\chrome\application\chrome --allow-file-access-from-files
如果您觉得有帮助,我已将下面的内容变成我使用的.bat文件。
start "chrome" %localappdata%\google\chrome\application\chrome --allow-file-access-from-files
exit
要查看该标志是否已设置,您可以访问:chrome://version/
并查看“命令行”部分,您应该看到-allow-file-access-from-files
您最有可能需要至少使用管理员权限来运行此操作,我会提醒您使用此设置访问未知网站,因为他们可以利用您的设置并可能读取本地文件。
参考:Reference Link -Allow Local File Access in Chrome (Windows)