js读取json文件

1. 原生的两种方法

1.1 XMLHttpRequest

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

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

<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

<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模块

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为例:

python -m http.server 8000

3.3 修改本地浏览器设置

修改本地浏览器设置, 以Windows平台谷歌浏览器为例, 启动时添加参数–allow-file-access-from-files
在这里插入图片描述

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值