【发布时间】:2018-03-04 14:58:46
【问题描述】:
我在使用本地机器上的 json 文件中的数据时遇到问题,我尝试了所有阅读的内容,但没有成功...
关注我的代码
Fetch API 无法加载 file:category.json。对于 CORS 请求,URL 方案必须是“http”或“https”。 (匿名)@ main.js:69 main.js:69 Uncaught (in promise) TypeError: Failed to fetch
关注我的代码
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<link rel="stylesheet" href="style.css" media="all">
</head>
<body>
<section id="ranking"></section>
<script src="main.js"></script>
</body>
</html>
(() => {
'use strict';
const calcPercentage = (negative, positive) => {
negative = null || undefined !== negative ? Number(negative) : 0;
positive = null || undefined !== positive ? Number(positive) : 0;
let total = negative + positive;
return {
negative: 0 !== total ? Math.floor((negative / total) * 100) : 0,
positive: 0 !== total ? Math.floor((positive / total) * 100) : 0
}
};
const changeItems = items => {
let percent;
return items.map(curr => {
percent = calcPercentage(curr.negative, curr.positive);
curr.negative = percent.negative;
curr.positive = percent.positive;
return curr;
});
};
const sortItems = items => {
items.sort((a, b) => {
if (a.positive > b.positive) {
return -1;
}
return 1;
})
return items;
};
const displayData = (data, parentEl) => {
const elements = [];
parentEl = document.getElementById(parentEl);
data.forEach((item, index) => {
elements.push(`
<div class="celebrity">
<h3>${item.name}</h3>
<p>${item.description}</p>
<div class="tooltip">
<div class="option">
<span class="left-radius right-pipe">OK</span>
<p class="left-radius right-pipe">${item.positive}%</p>
</div>
<div class="option">
<span class="right-radius">Don't</span>
<p class="right-radius">${item.negative}%</p>
</div>
</div>
</div>
`);
});
parentEl.innerHTML = elements.join('');
};
fetch('category.json',{
method: 'GET',
headers:{
'Access-Control-Allow-Origin':'*',
"Content-Type": "text/plain"
}
})
.then(response => response.json())
.then(data => changeItems(data.data))
.then(data => sortItems(data))
.then(data => displayData(data, 'ranking'))
})();
【问题讨论】:
-
您的网页 URL 是否读取 localhost 以获取文件:///。如果是后者,则浏览器会阻止所有非 Web 服务器访问。您必须在 Web 服务器上运行您的代码。
-
除了@jeff 的评论,XAMPP 之类的程序也可以用来模拟网络服务器。
-
只需要搭建一个小型的web服务器,就可以从localhost访问页面了。你不必安装 XAMPP,例如 Sublime Text 和其他文本编辑器都有它的插件。
-
所以......所有这些代码和问题都与它无关......大声笑
标签: javascript jquery json