【发布时间】:2020-08-03 16:11:27
【问题描述】:
我要做的就是访问 json 文件的内容并将它们显示到网页上。但我收到了这个错误:
Access to XMLHttpRequest at 'file:///C:/Users/bobal/Documents/htmlTry/myData.json' from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.
JSON 文件和 HTML 文件都在同一个文件夹中。
这是我的html页面:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"> </script>
<script>
$(function() {
var people = [];
$.getJSON('Assets/myData.json', function(data) {
$.each(data.person, function(i, f) {
var tblRow = "<tr>" + "<td>" + f.firstName + "</td>" +
"<td>" + f.lastName + "</td>" + "<td>" + f.job + "</td>" + "<td>" + f.roll + "</td>" + "</tr>"
$(tblRow).appendTo("#userdata tbody");
});
});
});
</script>
</head>
<body>
<div class="wrapper">
<div class="profile">
<table id= "userdata" border="2">
<thead>
<th>First Name</th>
<th>Last Name</th>
<th>Email Address</th>
<th>City</th>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
</body>
</html>
这里是 JSON 文件,myData.json:
{
"person": [
{
"firstName": "Clark",
"lastName": "Kent",
"job": "Reporter",
"roll": 20
},
{
"firstName": "Bruce",
"lastName": "Wayne",
"job": "Playboy",
"roll": 30
},
{
"firstName": "Peter",
"lastName": "Parker",
"job": "Photographer",
"roll": 40
}
]
}
我真的不明白这个问题,但如果我做错了,有人可以告诉我一个更好的方法吗?
【问题讨论】:
-
你有某种后端吗?
-
不,我想知道这是否是个问题,但我忘了提及。但是,对于我正在尝试做的事情,我真的没有任何类型的后端。我仅限于 JS、HTML 和 CSS。
-
那么纯html,css,js。有没有像nodejs/react/angular这样的框架?
-
不,我正在参加初学者网络开发课程,因为我需要额外的时间。我知道如何访问外部 API 并处理节点或 dotNet 或其他东西中返回的 JSON 对象,但我无法像这样简单地完成它
-
不要误会我的意思。我只是想确保没有其他框架导致问题。
标签: javascript html jquery json cors