javascript - 无法从本地 html 页面使用 ajax 本地文件

标签 javascript jquery ajax html

根据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/

相关文章:

jquery - 隐藏、显示、隐藏/显示按钮

javascript - 让我的搜索框容易受到 XSS 攻击

php - 缓存 AJAX 请求

javascript - CodeIgniter 在 AJAX 调用中一段时间​​后丢失 session

ruby-on-rails - 如何进行ajax调用将数据发送到rails Controller 并返回数据?

jquery - 当字段处于焦点时,Mousetrap.bind 不起作用?

javascript - 函数返回所有属性,但必须只返回被调用的属性

javascript - 无法更改 jquery 自动完成中的文本值

javascript - 不要在 WebStorm 的预提交中重新格式化 JSX 解构代码样式

java - Linux + 动态插入的 Java applet = 在 NPObject 上调用方法时出错