从单独的 JSON 文件加载数据,我需要进行哪些更改?

这里可能是一个非常新手的问题,但无论如何这里都是。


我最近在我的网站上实现了这个 javascript的一个版本来显示博客文章摘要。


我想知道我需要进行哪些更改才能让它加载相同的字段但从单独的 JSON 文件中获取数据,而不是在同一个文件中包含类似 JSON 的信息?


我自己也尝试过,但我无法完全解决。


我在代码中与链接中的代码的唯一主要区别是我在最后的位中有“切片”而不是“加入”。


任何帮助将不胜感激,因为我对 Javascript 非常陌生。


  const petsData = [

  {

    name: "Purrsloud",

    species: "Cat",

    favFoods: ["wet food", "dry food", "<strong>any</strong> food"],

    birthYear: 2016,

    photo: "https://learnwebcode.github.io/json-example/images/cat-2.jpg"

  },

  {

    name: "Barksalot",

    species: "Dog",

    birthYear: 2008,

    photo: "https://learnwebcode.github.io/json-example/images/dog-1.jpg"

  },

  {

    name: "Meowsalot",

    species: "Cat",

    favFoods: ["tuna", "catnip", "celery"],

    birthYear: 2012,

    photo: "https://learnwebcode.github.io/json-example/images/cat-1.jpg"

  }

];


function age(birthYear) {

  let calculatedAge = new Date().getFullYear() - birthYear;

  if (calculatedAge == 1) {

    return "1 year old";

  } else if (calculatedAge == 0) {

    return "Baby";

  } else {

    return `${calculatedAge} years old`;

  }

}


function foods(foods) {

  return `

<h4>Favorite Foods</h4>

<ul class="foods-list">

${foods.map(food => `<li>${food}</li>`).join("")}

</ul>

`;

}


function petTemplate(pet) {

  return `

    <div class="animal">

    <img class="pet-photo" src="${pet.photo}">

    <h2 class="pet-name">${pet.name} <span class="species">(${pet.species})</span></h2>

    <p><strong>Age:</strong> ${age(pet.birthYear)}</p>

    ${pet.favFoods ? foods(pet.favFoods) : ""}

    </div>

  `;

}


document.getElementById("app").innerHTML = `

  <h1 class="app-title">Pets (${petsData.length} results)</h1>

  ${petsData.map(petTemplate).slice(0, 2)}

  <p class="footer">These ${petsData.length} pets were added recently. Check back soon for updates.</p>

`;


扬帆大鱼
浏览 168回答 2
2回答

慕容3067478

您可以通过XMLHttpRequest从 json 中获取数据这里有一个示例代码:let xhr = new XMLHttpRequest();xhr.open("GET", "petsData.json");xhr.addEventListener("readystatechange", function () {&nbsp;// any change in the request will result in calling this function&nbsp;// here you can check the readyState of the request (4 means DONE)&nbsp;// we want also the status to be 200 OK&nbsp;if (xhr.readyState === 4 && xhr.status === 200) {&nbsp; // here you are sure that the data has been fetched correctly&nbsp; let response = xhr.response;&nbsp; /* DO SOMETHING WITH response */&nbsp;}});xhr.send();

慕后森

最快和最简单的方法是变通,创建一个 petsData.js 文件:export default {&nbsp;petsData: [&nbsp; {&nbsp; &nbsp; name: "Purrsloud",&nbsp; &nbsp; species: "Cat",&nbsp; &nbsp; favFoods: ["wet food", "dry food", "<strong>any</strong> food"],&nbsp; &nbsp; birthYear: 2016,&nbsp; &nbsp; photo: "https://learnwebcode.github.io/json-example/images/cat-2.jpg"&nbsp; }}并在您需要的任何地方导入(如有必要,更新文件路径),如下所示:import petsData from "./petsData.js";console.log(petsData.petsData)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript