使用JavaScript在页面上显示JSON
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了使用JavaScript在页面上显示JSON相关的知识,希望对你有一定的参考价值。
我不知道为什么下面代码片段中的代码会在'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>
答案
您必须解析对JSON的响应。
JSON.parse(response);
在每次通话之前插入它。这样你就可以迭代它并获得特定的对象。
另一答案
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之后,我想出了如何做到这一点
以上是关于使用JavaScript在页面上显示JSON的主要内容,如果未能解决你的问题,请参考以下文章
将 Mongoose 文档中的 JSON 数据返回到客户端 Javascript