gpt4 book ai didi

javascript - 在 HTML : Uncaught TypeError: data. forEach 中使用 JSON 文件不是函数

转载 作者:行者123 更新时间:2023-11-29 17:57:08 25 4
gpt4 key购买 nike

我浏览了网络/文档,但无法找出为什么这不起作用。

我正在尝试从 JSON 文件中插入数据(引号): {

"quotesArray":[{
"personName": "Albert Einstein",
"quote": "Look deep into nature, and then you will understand everything better."
},
{
"personName": "Stephen Hawking",
"quote": "Look deep into nature, and then you will understand everything better."
},
{
"personName": "Confucius",
"quote": "Life is really simple, but we insist on making it complicated."
}]}

使用以下 JS 进入一个简单的 HTML div:

 $(document).ready(function() {
$("#realquote").on("click", function() {
$.getJSON('/json/quotes.json', function(data) {
var html = " ";
data.forEach(function(val) {
var keys = Object.keys(val);
html += "<div class = 'text-output'>";
keys.forEach(function(key){
html += val[key];

});
html += "</div>"
});


$(".realquote").html(html);
});
});
});

但每次,我都会收到错误:TypeError: data.forEach is not a function",我不知道为什么。

如果有人能将我推向正确的方向,将不胜感激!

最佳答案

data 是一个没有.forEach 方法的常规对象。您应该遍历对象的 quotesArray 属性。

data.quotesArray.forEach(fn);

关于javascript - 在 HTML : Uncaught TypeError: data. forEach 中使用 JSON 文件不是函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38104612/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com