js读取json文件

1. 原生的两种方法

1.1 XMLHttpRequest

javascript 复制代码
const xhr = new XMLHttpRequest();
xhr.overrideMimeType("application/json");
xhr.open('GET', 'data.json', true);
xhr.onreadystatechange = function () {
  if (xhr.readyState === 4 && xhr.status === 200) {
    const data = JSON.parse(xhr.responseText);
    // 对象中的属性可以像平常一样访问
    console.log(data);
  }
};
xhr.send(null);

1.2 使用浏览器原生的fetch API

javascript 复制代码
fetch('data.json')
  .then(response => response.json())
  .then(data => {
    // 在这里可以操作读取到的 JSON 数据对象
    console.log(data);
  })
  .catch(error => {
    // 处理错误情况
    console.error('Error reading the JSON file:', error);
  });

2. 引入库的方法

2.1 Axios

javascript 复制代码
<script src="https://cdn.bootcdn.net/ajax/libs/axios/1.3.6/axios.js"></script>

axios.get('data.json')
  .then(response => {
    const data = response.data;
    // 对象中的属性可以像平常一样访问
    console.log(data);
  })
  .catch(error => {
    console.error('Error reading the JSON file:', error);
  });

2.2 jQuery中的getJSON

javascript 复制代码
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

$.getJSON("data.json", function (data) {
   	console.log(data)
});

2.3 Node.js中的fs模块

javascript 复制代码
const fs = require('fs');

fs.readFile('data.json', 'utf8', (err, data) => {
  if (err) {
    console.error('Error reading the file:', err);
    return;
  }
  const jsonContent = JSON.parse(data);
  // 对象中的属性可以像平常一样访问
  console.log(jsonContent);
});

3. 跨域问题

3.1 使用Live Server

3.2 在本地启动一个服务

给网页添加一个域名, 比如localhost, 我们可以使用python或者nodejs在本地启动一个服务, 这里以python3为例:

javascript 复制代码
python -m http.server 8000

3.3 修改本地浏览器设置

修改本地浏览器设置, 以Windows平台谷歌浏览器为例, 启动时添加参数--allow-file-access-from-files

相关推荐
A_aspectJ6 分钟前
Java开发的学习优势:稳定基石与多元可能并存的技术赛道
java·开发语言
qq_283720058 分钟前
Python 模块精讲:collections —— 高级数据结构深度解析(defaultdict、Counter、deque)
java·开发语言
一颗青果10 分钟前
Cookie 与 Session 超详细讲解
服务器·前端·github
zs宝来了17 分钟前
React 18 并发模式:Fiber 架构与时间切片
前端·javascript·框架
wjs202419 分钟前
Chart.js 饼图指南
开发语言
YSF2017_324 分钟前
C语言-12-静态库制作
c语言·开发语言
万物得其道者成27 分钟前
Vue3 使用 Notification 浏览器通知,解决页面关闭后旧通知点击无法跳转问题
前端·vue.js·edge浏览器
ShineWinsu30 分钟前
CSS 技术文章
前端·css
天若有情67340 分钟前
反向封神!C++ 全局单例不避反用,实现无锁多线程函数独占访问
java·javascript·c++
张风捷特烈41 分钟前
状态管理大乱斗#02 | Bloc 源码全面评析
android·前端·flutter