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

相关推荐
爱学习的程序媛3 分钟前
【Web前端】Vue2与Vue3核心概览与优化对比
前端·javascript·vue.js·typescript
li@h17 分钟前
如何在电脑端访问小程序时在胶囊添加一个全屏和缩放功能
前端
程序猿_极客21 分钟前
【2025最新】 Java入门到实战:包装类、字符串转换、equals/toString + 可变字符串,一篇搞定开发高频场景(含案例解析)
java·开发语言·java进阶·面试核心·java快速入门
U***e6331 分钟前
Python测试
开发语言·python
yi碗汤园1 小时前
Visual Studio常用的快捷键
开发语言·ide·c#·编辑器·visual studio
i_am_a_div_日积月累_1 小时前
JSON数据转Excel
json·excel·css3
aiguangyuan1 小时前
React 18 源码解读(一)
javascript·react·前端开发
LFly_ice1 小时前
学习React-23-React-router
前端·学习·react.js
Elias不吃糖1 小时前
NebulaChat:C++ 高并发聊天室服务端
开发语言·c++·redis·sql·项目文档
haofafa1 小时前
JavaScript性能优化实战
开发语言·javascript·性能优化