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

相关推荐
Wzx1980124 分钟前
go基础语法练习
开发语言·后端·golang
Mintopia6 分钟前
🧠 量子计算对AIGC的潜在影响:Web技术的未来可能性
前端·javascript·aigc
街尾杂货店&7 分钟前
css - word-spacing 属性(指定段字之间的间距大小)属性定义及使用说明
前端·css
忧郁的蛋~24 分钟前
.NET异步编程中内存泄漏的终极解决方案
开发语言·前端·javascript·.net
2301_7951672029 分钟前
玩转Rust高级应用. ToOwned trait 提供的是一种更“泛化”的Clone 的功能,Clone一般是从&T类型变量创造一个新的T类型变量
开发语言·后端·rust
水月wwww33 分钟前
vue学习之组件与标签
前端·javascript·vue.js·学习·vue
你才是向阳花41 分钟前
如何用Python实现飞机大战小游戏
开发语言·python·pygame
合作小小程序员小小店1 小时前
web网页开发,在线%商城,电商,商品购买%系统demo,基于vscode,apache,html,css,jquery,php,mysql数据库
开发语言·前端·数据库·mysql·html·php·电商
顾安r1 小时前
11.8 脚本网页 塔防游戏
服务器·前端·javascript·游戏·html
草莓熊Lotso1 小时前
C++ 方向 Web 自动化测试实战:以博客系统为例,从用例到报告全流程解析
前端·网络·c++·人工智能·后端·python·功能测试