如何使用Javascritp读取txt文件中的节点

时间:2018-06-22 02:44:22

标签: javascript json xmlhttprequest

我需要创建一个类似

的列表
  • 动物1
  • 动物2
  • 动物3

响应位于带有某些节点的.TXT文件中

{
    "pets":[
        { "animal":"animal 1", "name":"Fido" },
        { "animal":"animal 2", "name":"Felix" },
        { "animal":"animal 3", "name":"Lightning" }
    ]
}

如何创建JS以在DIV中返回动物的名字?

2 个答案:

答案 0 :(得分:0)

可能有比我更好的方法,但这是有的。

您可以使用for loop遍历对象,如下所示:

const response = {
  "pets": [{
      "animal": "animal 1",
      "name": "Fido"
    },
    {
      "animal": "animal 2",
      "name": "Felix"
    },
    {
      "animal": "animal 3",
      "name": "Lightning"
    }
  ]
};

// Loop through the pets property of the response object
for (let i = 0; i < response.pets.length; i++) {
  // Add the name property of the pets property to the div
  document.getElementById('animals').innerHTML += `${response.pets[i].name} <br>`;
}
<div id="animals"></div>

答案 1 :(得分:0)

检查以下代码。希望对您有所帮助:)

let response = {
  "pets": [{
      "animal": "animal 1",
      "name": "Fido"
    },
    {
      "animal": "animal 2",
      "name": "Felix"
    },
    {
      "animal": "animal 3",
      "name": "Lightning"
    }
  ]
}

function getAnimals() {
  let html = '';
  response.pets.forEach(animal => {
    html += `<div>${animal.name}</div>`;
  });
  console.log(html)
}
getAnimals();