【问题标题】:Ajax in Jquery does not work from local fileJquery 中的 Ajax 不适用于本地文件
【发布时间】:2013-07-30 15:44:20
【问题描述】:

我用简单的 ajax 创建了简单的 html 文件。

index.html

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; Charset=UTF-8">
<script type="text/javascript" src="jquery.js"></script>
</head>
<body>
    <div id="content"></div>

    <script>
        function show()
        {
                $.ajax({
                url: "2.html",
                cache: false,
                success: function(html){
                    $("#content").html(html);
                }
            });
        }

        $(document).ready(function(){
            show();
            setInterval('show()',1000);
        });
    </script>

</body>
</html>

文件 2.html 与文件 index.html 位于同一目录中。并包含例如:

 <p>ssss hkl jh lkh <b>d1111</b></p>

当我在网络服务器上运行 index.html 时,一切正常。但是,如果您在计算机上运行文件 index.html 作为本地文件 ajax 不起作用。如何解决?

【问题讨论】:

  • jquery.js 是否包含在 index.html 旁边?
  • 您在 Chrome 中吗? Chrome 不允许使用本地 ajax 内容。

标签: jquery html ajax local


【解决方案1】:

这是 Chrome 的一个已知问题,如果您正在检查它。使用 XAMPP 运行本地网络服务器,并测试您的 ajax 调用。

查看这张票:https://code.google.com/p/chromium/issues/detail?id=40787

【讨论】:

  • 甚至更快,使用 Python(当然)。在终端中:cd /path/to/project/folder 然后&gt; python -m SimpleHTTPServer 8080 使用127.0.0.1:8080 或您的系统可能需要的变体。 (OSX,Py 2.7x)
  • 或者你可以使用 node.js。 > npm install -g http-server > cd /path/to/project/folder > http-server
【解决方案2】:

一些浏览器实施了强大的安全措施来防止下载的网页访问文件系统上的任意文件。

切换到安全性较弱的浏览器(我认为 Firefox 允许通过 XHR 访问本地文件)或停止尝试在没有 HTTP 的情况下运行网站。

【讨论】:

  • 还有 chrome 和下面的命令行:chrome --allow-file-access-from-files
猜你喜欢
  • 2016-06-21
  • 1970-01-01
  • 1970-01-01
  • 2011-03-28
  • 1970-01-01
  • 1970-01-01
  • 2022-10-18
  • 2013-07-08
  • 2012-09-17
相关资源
最近更新 更多