js如何获取本地json数据
- 编程技术
- 2025-02-01 22:38:16
- 1
在JavaScript中获取本地JSON数据通常有以下几种方法: 1. 使用 `fetch` API`fetch` API 可以用来获取服务器上的资源,但也可以用来读取...
在JavaScript中获取本地JSON数据通常有以下几种方法:
1. 使用 `fetch` API
`fetch` API 可以用来获取服务器上的资源,但也可以用来读取本地文件。假设你有一个名为 `data.json` 的文件,你可以这样读取:
```javascript
fetch('data.json')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
```
2. 使用 `XMLHttpRequest`
这是一个更传统的获取数据的方法,可以用来读取本地文件:
```javascript
var xhr = new XMLHttpRequest();
xhr.open('GET', 'data.json', true);
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
var data = JSON.parse(xhr.responseText);
console.log(data);
本文由夕逆IT于2025-02-01发表在夕逆IT,如有疑问,请联系我们。
本文链接:http://xinin56.com/bian/424610.html
本文链接:http://xinin56.com/bian/424610.html
上一篇:神雕侠侣中王处一去哪儿了