文件包含:
- data.json
- index.html
需要实现的功能为本地读取json文件,进行列表展示
遇到问题:
使用jQuery请求本地的json文件
在script标签中引入JQuery
- 方案1:
$.getJSON("data.json", function (data) {
console.log(data[first]);
});
- 产生跨域
- 产生原因
So when you call $.getJSON() you are actually executing an GET call as described in the JQuery docs here. https://api.jquery.com/jQuery.getJSON/ Because of that the browser will enforce CORS, even if you are using the file protocol.
在这种情况下实际是一个get请求
-
解决方案:
使用HTML5的Files API
API文档-readAsText()
然后再JSON.parse() -
方案2:
使用ajax请求+vscode插件live server -
解决方案:
临时:使用vscode自带的live server
插件安装完成后,右键需要打开的html文件会有Open With Live Server
最终:服务器这里允许CORSAccess-Control-Allow-Origin: *
最终代码如下:
- data.json
{
"first":[
{"name":"张三","sex":"男"},
{"name":"李四","sex":"男"},
{"name":"王武","sex":"男"},
{"name":"李梅","sex":"女"}
]
}
- index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.js"></script>
</head>
<body>
<div id ="listShow"></div>
<script>
var Ajax = function () {
//在vscode环境这个获取本地json文件中的数据
//可以使用vscode中的live server插件解决跨域问题
//ajax请求可以通过引入jquery进行调用
$.ajax({
url: "data.json",
type: "GET",
success: function (res) {
data = res["first"];
var str = "<table>";
for (var index in data) {
str += "<tr><td>" + data[index].name + "</td><td>" + data[index].sex + "</td></tr>";
};
str += "</table>";
document.getElementById("listShow").innerHTML = str;
},
error: function (res) {
console.log("发生错误");
console.log(res);
}
})
}
Ajax();
</script>
</html>