javascript - 我在 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>
解决方案
使用安全策略,您不能使用file:///
协议请求文件。因此,您需要设置一个服务器,以提供您想要通过 ajax 获取的文件。
推荐阅读
- c++ - 内联是否确定内部链接?
- javascript - 从浏览器中的另一个 js 文件访问一个 js 文件中的私有变量和方法
- c - 作业问题,国际象棋皇后的可用字段
- linux - Sublime Build 编译和运行 JavaFX 代码
- rust - tokio::net::TcpStream 是如何实现 tokio::prelude::Stream 的?
- java - 将@Transactional 与“jpaApi.withTransaction”混合是否有问题?
- r - 几列的乘法
- flutter - 颤振着色背景扩展面板列表
- google-cloud-dataflow - Stateful DoFn 如何确定分区状态的关键
- azure - 从 AKS 群集访问 Azure 存储 Blob