首页 > 解决方案 > 我在 ajax 中的 XMLHttpRequest 在 Chrome 中不起作用

问题描述

我是学习ajax的新手。当我运行我的代码时,会显示此错误。

“CORS 策略已阻止从源“null”访问 'file:///.../text.txt' 处的 XMLHttpRequest:跨源请求仅支持协议方案:http、data、chrome、chrome-extension ,https。

text.txt:1 加载资源失败:net::ERR_FAILED"

这里有什么问题?

这是代码:

<!DOCTYPE html>
<html>
  <body>

    <h2>The XMLHttpRequest Object</h2>

    <p id="demo">Let AJAX change this text.</p>

    <button type="button" onclick="loadDoc()">Change Content</button>

    <script>
      function loadDoc() {
        var xhttp = new XMLHttpRequest();
        xhttp.onreadystatechange = function() {
          if (this.readyState == 4 && this.status == 200) {
            document.getElementById("demo").innerHTML = this.responseText;
          }
        };
        xhttp.open("GET", "text.txt", true);
        xhttp.send();
      }
    </script>

  </body>
</html>

标签: javascript

解决方案


使用安全策略,您不能使用file:///协议请求文件。因此,您需要设置一个服务器,以提供您想要通过 ajax 获取的文件。


推荐阅读