根据Same Origin Policy ,SOP 不应该适用于 file://协议(protocol),但为什么我的代码不起作用?我正在从本地系统运行此测试页面,并且 abc.txt 与 html 页面位于同一目录中。如果我将 URL 更改为 http://www.google.com/ ,它也不起作用。我不明白为什么,有人能解释一下吗?
<!doctype html>
<html lang="us">
<head>
<meta charset="utf-8">
<title>jQuery UI Example Page</title>
<link href="css/sunny/jquery-ui-1.10.2.custom.css" rel="stylesheet">
<script src="js/jquery-1.9.1.js"></script>
<script src="js/jquery-ui-1.10.2.custom.js"></script>
<script>
$.support.cors = true;
$(function(){
$(".btn1").button().click(function(){
$.ajax({
url: "abc.txt"
}).done(function(result) {
alert("done");
$(".content").html(result);
}).fail(function() {
alert("error");
});
});
});
</script>
</head>
<body>
<button class="btn1">Click me!</button>
<div class="content"></div>
</body>
</html>
编辑: 控制台打印如下:
XMLHttpRequest cannot load file:///C:/Users/yc/Desktop/jquery%20ajax%20testing/jquery-ui-1.10.2.custom/jquery-ui-1.10.2.custom/abc.txt. Origin null is not allowed by Access-Control-Allow-Origin.
*它不适用于 Firefox、IE。
最佳答案
这不是错误,而是您无法/不会在客户端计算机上绕过的安全功能。
在 Chrome 中,您可以通过在命令行上添加以下标志来禁用它
--禁用网络安全
Firefox 可能有类似的东西,但我不知道。这仅对开发目的有用,您不能在应用程序中依赖此行为。
你真的应该只使用服务器......
关于javascript - 无法从本地 html 页面使用 ajax 本地文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16683600/