报错
Access to XMLHttpRequest at ‘file:///C:/Users/…/xx.json’ from origin ‘null’ has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome-extension, edge, https, chrome-untrusted.
分析原因
浏览器访问本机文件受限,json文件为本地文件,html运行调试时,在默认浏览器中打开其域名为“file:///C:/Users/…html”。访问本机文件需设法将域名改为localhost,本文采用jquery读取本地json文件,操作简便,具体方法如下:
编译器
Visual Studio Code
所需插件:live-server
操作步骤
在Visual Studio Code扩展中安装live-server如图所示
在html头部引入jquery
<head>
<!-- 引入jquery -->
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
</head>
调用getJSON函数获取本地json文件信息(显示在控制台)
<script>
$.getJSON("./renyuanxinxi.json",function(data){
console.log('data--',data);
})
</script>
右键选择Open with live server