【发布时间】:2019-07-09 15:32:16
【问题描述】:
我正在尝试在 github 中请求一个 json 文件(例如:http://github/..file.json),我有一个 javascript 代码(没有 jquery),这与 this question 不同,它使用它来请求带有 ajax 的文件。
index.js
function fetchJSONFile(path, callback) {
var httpRequest = new XMLHttpRequest();
httpRequest.onreadystatechange = function() {
if (httpRequest.readyState === 4) {
if (httpRequest.status === 200) {
var data = JSON.parse(httpRequest.responseText);
if (callback) callback(data);
}
}
};
httpRequest.open('GET', path);
httpRequest.send();
}
let button = document.createElement('button');
button.addEventListener("click", function () {
// this requests the file and executes a callback with the parsed result once it is available
fetchJSONFile('https://github.com/.../file.json', function(data){
// do something with your data
console.log(data);
});
});
button.appendChild(document.createTextNode('JSON parse'));
document.body.appendChild(button); // append in body html
index.html
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<script src="index.js" charset="utf-8"></script>
</body>
</html>
我在没有本地服务器(apache 等)的情况下在浏览器中打开 index.html,然后单击按钮返回以下警告
访问 XMLHttpRequest 在 'https://github.com/.../file.json' 来自原点“null”已被 CORS 策略阻止:否 请求中存在“Access-Control-Allow-Origin”标头 资源。
index.js:12 Cross-Origin Read Blocking (CORB) 阻止了跨域 回复 https://github.com/.../file.json MIME 类型为 text/html。看 https://www.chromestatus.com/feature/5629709824032768 了解更多 详情。
通常(在我的工作流程中)我创建了对同一本地服务器的 ajax 请求,并且我混淆了一些类似 CORS 的概念(不知道)
【问题讨论】:
标签: javascript html json ajax