【问题标题】:Couldn't ajax local file from local html page无法从本地 html 页面 ajax 本地文件
【发布时间】: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


【解决方案1】:

比 ''--disable-web-security'' 稍微安全的命令行标志是

--allow-file-access-from-files

这不会完全关闭所有安全功能。这个标志也不应该在生产环境中使用......

【讨论】:

    【解决方案2】:

    这不是错误,而是您无法/不会在客户计算机上使用的安全功能。

    在 chrome 中,您可以通过在命令行中添加以下标志来禁用它

    --disable-web-security

    Firefox 可能有类似的东西,但我不知道。这仅对开发目的有用,您不能在应用程序中依赖此行为。

    你真的应该只使用服务器......

    【讨论】:

    • 第二个选项不再是有效的规避 - 通过编辑删除。
    • @smaudet 编辑请求被拒绝。留下评论就足够了,然后由答案的作者决定是否应该从答案中删除辅助选项。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-02-27
    • 1970-01-01
    • 2016-02-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-13
    相关资源
    最近更新 更多