我有一些简单的代码试图发出 ajax 请求。我尝试使用 .txt 文件并发现 CORS 错误。然后我尝试使用带有 header("Access-Control-Allow-Origin: *"); 的 php 文件 因为我听说这是在任何浏览器上允许所有 ajax 调用的最简单方法。我浏览了许多 SO 帖子并到处搜索,似乎找不到解决方案。这是我的文件。我将包含 .txt 文件,但我已经明白为什么该文件不起作用。
ajax-1.html
<!DOCTYPE html>
<html>
<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="button">Get Text File</button>
<br><br>
<div id="text">
</div>
<script>
//create event listener
document.getElementById('button').addEventListener('click', loadText);
function loadText() {
//create an object
const xhr = new XMLHttpRequest();
//open - type, url/file, async t/f
xhr.open('get', 'sample.php', true);
console.log('READYSTATE: ', xhr.readyState);
//OPTIONAL - used for loaders
xhr.onprogress = function () {
console.log('READYSTATE: ', xhr.readyState);
}
xhr.onload = function () {
console.log('READYSTATE: ', xhr.readyState);
if (xhr.status == 200) {
// console.log(this.responseText);
document.getElementById('text').innerHTML = this.responseText;
} else {
document.getElementById('text').innerHTML = 'Not Found';
}
}
xhr.onerror = function () {
console.log('request error');
}
//sends request
xhr.send();
}
</script>
</body>
</html>
示例.php
<?php
header("Access-Control-Allow-Origin: *");
echo "Some Lorem ipsum text";
?>
样本.txt
lorem ipsum
这是 chrome 控制台显示的内容
就绪状态:1
ajax1.html:1 从源“null”访问“file:///Users/macbookuser/Desktop/traversy/ajax/sample.php”处的 XMLHttpRequest 已被 CORS 策略阻止:跨源请求仅支持协议方案:http,数据,铬,铬扩展,https。ajax1.html:46 请求错误 ajax1.html:56 GET file:///Users/macbookuser/Desktop/traversy/ajax/sample.php net::ERR_FAILED
慕工程0101907