const xhr = new XMLHttpRequest();
xhr.open('GET', 'http://127.0.0.1:8080/抽卡记录.json', true);
xhr.onreadystatechange = function() {
  if (xhr.readyState === 4 && xhr.status === 200) {
    const json = JSON.parse(xhr.responseText);
    // 处理json数据
    json.info.forEach(item => {
      const li = document.createElement('li');
      li.textContent = `${item.name} - ${item.item_type}`;
      document.getElementById('jsonList').appendChild(li);
    });
  }
};
xhr.send();

在代码中,我假设你有一个id为jsonList的元素来承载列表。你需要将jsonList替换为你实际使用的元素id。这样,当请求成功后,会将抽卡记录中的名称和物品类型添加到列表中。

示例 JSON 数据:

{
  "info": [
    {
      "uid": "214634447",
      "gacha_type": "200",
      "item_id": "",
      "count": "1",
      "time": "2022-06-06 13:24:46",
      "name": "铁影阔剑",
      "lang": "zh-cn",
      "item_type": "武器",
      "rank_type": "3",
      "id": "1654491960001014347",
      "uigf_gacha_type": "200"
    },
    {
      "uid": "214634447",
      "gacha_type": "200",
      "item_id": "",
      "count": "1",
      "time": "2022-06-05 10:58:15",
      "name": "托马",
      "lang": "zh-cn",
      "item_type": "角色",
      "rank_type": "4",
      "id": "1654394760002450247",
      "uigf_gacha_type": "200"
    },
    {
      "uid": "214634447",
      "gacha_type": "200",
      "item_id": "",
      "count": "1",
      "time": "2022-06-04 16:56:41",
      "name": "弹弓",
      "lang": "zh-cn",
      "item_type": "武器",
      "rank_type": "3",
      "id": "1654329960002758347",
      "uigf_gacha_type": "200"
    },
    {
      "uid": "214634447",
      "gacha_type": "200",
      "item_id": "",
      "count": "1",
      "time": "2022-06-04 15:43:53",
      "name": "雨裁",
      "lang": "zh-cn",
      "item_type": "武器",
      "rank_type": "4",
      "id": "1654326360002287147",
      "uigf_gacha_type": "200"
    }
  ]
}

代码功能解析:

  1. 创建 XMLHttpRequest 对象
  2. 使用 open() 方法设置请求方式、URL 和是否异步
  3. 使用 onreadystatechange 事件监听请求状态变化
  4. 当请求完成且状态码为 200 时,解析 JSON 数据
  5. 遍历 JSON 数据中的 info 数组,为每个抽卡记录创建一个列表项 li
  6. 将列表项添加到 jsonList 元素中
使用 JavaScript 从 JSON 文件读取抽卡记录并展示

原文地址: https://www.cveoy.top/t/topic/qnOb 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录