我是新手,正在学习 AJAX 的基础知识。在我的 HTML 文件中,当点击提交按钮时,我只是尝试记录文本文件的文本,该文本文件位于 HTML 文件所在的同一目录中。但是我却收到了一个错误:
Access to XMLHttpRequest at 'file:///D:/Front_end_files/AJAX/sample.txt' from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.
这是我的 Ajax-1.html
文件:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Ajax-1 Text file</title>
</head>
<body>
<button id="btn">Click Me</button>
<script>
document.getElementById('btn').addEventListener('click',loadtext);
function loadtext(){
let xhr = new XMLHttpRequest();
console.log(xhr);
xhr.open('GET', 'sample.txt', true);
xhr.onload = function(){
if(this.status == 200){
console.log(this.responseText);
}
};
xhr.send();
}
</script>
</body>
</html>
有人能告诉我在这里我做错了什么,还是这是chrome和firefox的新功能?
python -m http.server [<portNo>]
。 - nwhaughtpython3 -m http.server
,参考这篇博客文章。 - John Skiles Skinner