首页 > 解决方案 > 如何从本地文件中读取 Json

问题描述

我使用inspect来检查,它显示如下:lottie.js:3 Failed to load file:///Users/Downloads/ani/js/data.json: 跨源请求仅支持协议方案:http、data、铬,铬扩展,https。

我不知道如何从本地服务器的 .json 文件中读取 Json?谁能帮我解决它?

var animation = bodymovin.loadAnimation({
  container: document.getElementById('Ani'),
  renderer: 'svg',
  loop: true,
  autoplay: true,
  path: 'js/data.json'
})
<!DOCTYPE html>
<html>
<head>
  
  <!--  Meta  -->
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Bodymovin Demo</title>
  <!--  Styles  -->
  <style>
   #Ani{max-width: 800px; margin:0 auto;}
  </style>
  
</head>
<body>
  
  <div id="Ani"> </div>
  
<!-- Scripts -->
<script src="js/lottie.js"></script>
<script src="js/script.js"></script>
</body>
</html>

标签: javascripthtmljsonweb

解决方案


您正在使用file协议打开文件并尝试 Ajax 请求。那是行不通的。您最好通过服务器打开文件。您可以使用 apache 或任何网络服务器?例如,如果您熟悉 Node,则可以使用http-server 或使用lite-server

npm install http-server -g
http-server 'path/to/your/project' -o

这应该在以下位置打开浏览器窗口:localhost:8080 或其他端口(如果8080不是免费的)


推荐阅读