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

相关推荐
资深web全栈开发几秒前
JS防爬虫3板斧
开发语言·javascript·爬虫
Ulyanov5 分钟前
三维战场可视化核心原理(一):从坐标系到运动控制的全景指南
开发语言·前端·python·pyvista·gui开发
java1234_小锋5 分钟前
Java项目中如何选择垃圾回收器?
java·开发语言
zhangjin11208 分钟前
java线程的阻塞和等待的区别
java·开发语言
ChindongX11 分钟前
garbage at the end of the document
qt·json
天若有情67312 分钟前
从语法拆分到用户感知:我的前端认知重构之路
前端·javascript
未来可期LJ14 分钟前
【Qt 开发】Qt QFileDialog 文件对话框详解
开发语言·qt
SilentSlot15 分钟前
【QT-QML】2. QML语法
开发语言·qt·qml
_OP_CHEN15 分钟前
【前端开发之CSS】(五)CSS 盒模型深度解析:从基础到实战,掌控页面布局核心
前端·css·html·盒模型·页面开发·页面布局·页面美化
轩情吖16 分钟前
Qt常用控件之QDial和QSlider
开发语言·qt