js怎么导入json文件

  • 文章介绍
  • 热门推荐
  • 热门内容

如何在 JavaScript 中导入 JSON 文件

导入 JSON 文件的步骤:

  1. 创建 XMLHttpRequest 对象:

    const request = new XMLHttpRequest();
  2. 设置请求类型和 URL:

    request.open('GET', 'data.json');
  3. 设置请求头:

    request.setRequestHeader('Content-Type', 'application/json');
  4. 发送请求:

    request.send();
  5. 侦听响应:

    request.onload = function() {  if (request.status === 200) {    // 解析 JSON 文件    const data = JSON.parse(request.responseText);    // 使用数据...  }};

示例:

// 创建 XMLHttpRequest 对象const request = new XMLHttpRequest();// 设置请求类型和 URLrequest.open('GET', 'data.json');// 设置请求头request.setRequestHeader('Content-Type', 'application/json');// 发送请求request.send();// 侦听响应request.onload = function() {  if (request.status === 200) {    // 解析 JSON 文件    const data = JSON.parse(request.responseText);    // 输出数据    console.log(data);  }};

以上就是js怎么导入json文件的详细内容,更多请关注css网站其它相关文章!