我想用ajax做一些非常简单的事情。我的mac中有一个包含2个文档的文件夹:index.html和text.txt。
index.html:
<p>
<input type="button" onclick="loadDoc()" value="CLICK" />
</p>
<p id="fileContent"></p>
<script>
function loadDoc() {
var xhr = new XMLHttpRequest();
xhr.open('GET', "text.txt", true);
xhr.onreadystatechange = function() {
document.getElementById('fileContent').innerHTML = xhr.responseText;
}
xhr.send(null);
}
</script>
text.txt:
hello
当用户点击按钮CLICK时,我想要text.txt&#39;你好&#39;的内容。按下按钮CLICK。
它本地无法使用我的Mac。你知道为什么吗?
谢谢!
答案 0 :(得分:1)
大多数浏览器的正常行为。 ajax无法访问本地文件。这是一项安全功能。您可以运行某些开发服务器或使用--disabled-web-security标志启动chrome。然而,有一个新的html5本地文件访问API出现,因此我不确定它支持的程度如何...... http://www.html5rocks.com/en/tutorials/file/dndfiles/
答案 1 :(得分:0)
无法通过file:///
进行Ajax请求这是CORS的安全限制。
你拥有的是正确的。但需要通过http://