首页 > 解决方案 > 尝试从 JSON 文件中选择一个值以输出到 HTML

问题描述

所以我有 6 个 div,我想使用我提供的 JSON 代码将累积奖金值输出到每个 div。我的问题是我似乎无法选择累积奖金值,因为我收到以下错误。未捕获的类型错误:无法在 XMLHttpRequest.ourRequest.onload (js.js:10) 的 renderHTML (js.js:24) 处读取未定义的属性“大奖”

JSON

  {
  "jackpots": [
    {
      "jackpot": "417,961.29", 
      "game": "ElmStreet"
    }, 
    {
      "jackpot": "3,741,373.46", 
      "game": "MillionairGenie"
    }, 
    {
      "jackpot": "3,741,373.46", 
      "game": "TreasureFair"
    }, 
    {
      "jackpot": "70,004.09", 
      "game": "JacksPot"
    }, 
    {
      "jackpot": "14,749.68", 
      "game": "IrishRiches"
    }, 
    {
      "jackpot": "17,932.43", 
      "game": "CasinoReels"
    }
  ]
}

JS

    var pageCounter = 1;
var animalContainer = document.getElementsByClassName("jackpot");
var icon = document.getElementsByClassName('icon');
for (var i = 0 ; i < icon.length; i++) {
icon[i].addEventListener("click", function () {
  var ourRequest = new XMLHttpRequest();
  ourRequest.open('GET', 'http://www.json-generator.com/api/json/get/bZlZOVDMKq?indent=2');
  ourRequest.onload = function() {
      var ourData = JSON.parse(ourRequest.responseText);
      renderHTML(ourData);
      pageCounter++;
  };
  ourRequest.send();
})};

function renderHTML(data) {
  var htmlString = "";

for (var i = 0 ; i < animalContainer.length; i++) {
  animalContainer[i].innerHTML = "<p>" + data[i].jackpots.jackpot + "</p>"
 }
}

HTML

<section class="games-container">

    <div class="game Jackpot">
    <img class="icon" class="icon" src="jackpot.png" alt="">
    <label class="name" >Jackpot</label>
    <label class="jackpot" >$0</label>
    </div>

    <div class="game TreasureFair">
    <img class="icon" src="jackpot.png" alt="">
    <label class="name" >TreasureFair</label>
    <label class="jackpot" >$0</label>
    </div>

    <div class="game Millionaire Genie">
    <img class="icon" src="jackpot.png" alt="">
    <label class="name" >Millionaire Genie</label>
    <label class="jackpot" >$0</label>
    </div>

    <div class="game Irish Riches">
    <img class="icon" src="jackpot.png" alt="">
    <label class="name" >Irish Riches</label>
    <label class="jackpot" >$0</label>
    </div>

    <div class="game ElmStreet">
    <img class="icon" src="jackpot.png" alt="">
    <label class="name" >ElmStreet</label>
    <label class="jackpot" >$0</label>
    </div>

    <div class="game CasinoReels">
    <img class="icon" src="jackpot.png" alt="">
    <label class="name" >CasinoReels</label>
    <label class="jackpot" >$0</label>
    </div>

</section>

标签: javascriptjson

解决方案


在你引用数据的 for 循环中,data[i].jackpots.jackpot你试图引用的数组是“jackpots”而不是“data”,所以也许试试data.jackpots[i].jackpot.


推荐阅读