使用JavaScript在页面上显示JSON

时间:2017-12-30 11:43:49

标签: javascript json function dom xmlhttprequest

我不知道为什么以下代码段中的代码会在'generateSkillData'函数中返回此错误:

Uncaught TypeError: Cannot read property 'forEach' of undefined
    at generateSkillData (script.js:54)
    at loadingDone (script.js:45)
    at XMLHttpRequest.request.onload (script.js:24)

而不是显示skills.json的结果(参见下面一个对象的示例):

[
{
    "skill": "Python",
    "description": "An increasingly popular server-side language"
}
] 

我有其他非常相似的代码,运行正常。我从该代码中借用了很多功能。

function getSkillData(errorFunc, successFunc) {
  let request = new XMLHttpRequest();
  request.open("GET", "js/skills.json", true);
  request.onload = function() {
    if (request.status >= 200 && request.status < 400) {
      console.log("Success! The call worked!");
      const data = request.responseText;

      successFunc(data); {
        console.log("Error: no data available");
      }
    };
    request.onerror = function errorFunc() {
      errorFunc();
    };
  };

  request.send();
}

function loadingDone(data) {
  console.log("LOADING DONE");
  skill_box.innerHTML = "";
  const finished_markup = generateSkillData(data);
  const skill_container = document.getElementById("skill_box");
  skill_container.insertAdjacentHTML("beforeend", finished_markup);
};


function generateSkillData(response) {
  let skill_markup = "";
  response.data.forEach(function(thing) {
    skill_markup += formatSkillData(thing);
  });
  return skill_markup;
}

function formatSkillData(item) {
  const markup = `
        <ul>
            <li>${item.skill}</li>
            <li>${item.description}</li>
        </ul>`;
  return markup;
}

function loadingError() {
  console.log("Error loading skills: try again later");
  document.body.insertAdjacentHTML("beforeend", "<strong>An error occured, please try again later</strong>");
};


(function init() {
  getSkillData(loadingError, loadingDone);
})()
<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="">
  <title></title>
  <meta name="description" content="">
  <meta name="viewport" content="width=device-width, initial-scale=1">
</head>

<body>

  <form id="user_form">
    <label class="user_input_label" for="link">Skill name:</label>
    <input type="text" name="skill" value="" placeholder="Enter a skill..." id="skill">
    <label class="user_input_label" for="price">Skill description:</label>
    <input type="text" name="description" value="" placeholder="Description..." id="description">
    <input class="submit_button" type="submit" value="Submit">
  </form>

  <section id="skill_box">

  </section>

</body>

<script src="js/script.js"></script>

</html>

2 个答案:

答案 0 :(得分:1)

您必须解析对JSON的回复。

JSON.parse(response);

在每次通话之前插入它。 这样你就可以迭代它并获得特定的对象。

答案 1 :(得分:0)

const data = JSON.parse(request.responseText);  

在响应中使用console.log后,在此处添加了JSON.parse

function generateSkillData(response){
    let skill_markup = "";
    console.log(response);
    response.forEach(function (thing) {
        skill_markup += formatSkillData(thing);
    });
    return skill_markup;
}

在使用console.log之后,我想出了如何做到这一点