文件包含:
- 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":"男"