【发布时间】:2013-05-17 00:32:48
【问题描述】:
根据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 无法加载 file:///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也不行。
【问题讨论】:
-
尝试在你的ajax调用中设置
dataType: "text",选项.. -
您可以使用
--disable-web-security或--allow-file-access-from-files启动chrome -
控制台说什么
-
@PalashMondal 还是不行。
-
@iliacholy 这不仅发生在 chrome 上。我用的是firefox和IE,他们有同样的问题。
标签: javascript jquery ajax html