[英]Couldn't ajax local file from local html page
根据Same Origin Policy ,SOP不应应用于file://协议,但是为什么我的代码不起作用? 我正在从本地系统运行此测试页面,并且在与html页面相同的目录中有abc.txt。 如果我将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无法加载文件:/// C:/Users/yc/Desktop/jquery%20ajax%20testing/jquery-ui-1.10.2.custom/jquery-ui-1.10.2.custom/abc.txt。 Access-Control-Allow-Origin不允许使用Origin null。
*它也不适用于Firefox,IE。
这不是错误,它是您无法/不会在客户端计算机上使用的一项安全功能。
在chrome中,您可以通过在命令行上添加以下标志来禁用它
--disable-web-security
Firefox可能有类似的东西,但我不知道。 这仅对开发有用,您不能在应用程序中依赖此行为。
您真的应该只使用服务器...
比“ --disable-web-security”更安全的命令行标志是
--allow-file-access-from-files
这不会完全关闭所有安全功能。 同样,该标志也不应在生产环境中使用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.