gpt4 book ai didi

javascript - 遍历 JSON 数组 : uncaught syntax error, Uncaught ReferenceError

转载 作者:行者123 更新时间:2023-11-29 19:13:43 28 4
gpt4 key购买 nike

我对 JQuery 还是个新手,我正在尝试使用它遍历 JSON 数组并使用数组中的数据更新我的网页。

JSON 文件如下所示:

[
{
"firstname":"John",
"lastname":"Doe",
"studentnumber":"666"
},
{
"firstname":"Foo",
"lastname":"Bar",
"studentnumber":"777"
}
]

我的 HTML 文档如下所示:

<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="jquery-2.2.3.js"></script>
<script type="text/javascript">
$(document).ready(function(){
console.log('ready');
$.getJSON('us.json', function(data){
$.each(JSON.parse(data), function(key, value){
$.each(value, function(index, member){
html += '<div class="member">';
html += '<h4>' + member.firstname + ' ' + member.lastname +'</h2>';
html += '<p>' + 'has the following member number:' + member.studentnumber + '</p>';
html += '</div>';
console.log(html)
})
});
$('#members').html(html);
});
});
</script>
</head>

<body>
<div>
<h3>Members</h3>
</div>
<div id="members"></div>
</body>
</html>

您可以看到我正在尝试使用 .each 函数来完成此任务。上面的代码给出了以下错误:

VM2028:1 Uncaught SyntaxError: Unexpected token o
(anonymous function) @ index-v1.html:10
fire @ jquery-2.2.3.js:3187
self.fireWith @ jquery-2.2.3.js:3317
done @ jquery-2.2.3.js:8785
(anonymous function) @ jquery-2.2.3.js:9151

在这里查看之前的一些问题后,我尝试将 JSON.parse(data) 替换为 data,这导致了以下错误:

Uncaught ReferenceError: html is not defined
(anonymous function) @ index-v1.html:12
jQuery.extend.each @ jquery-2.2.3.js:371
(anonymous function) @ index-v1.html:11
jQuery.extend.each @ jquery-2.2.3.js:365
(anonymous function) @ index-v1.html:10
fire @ jquery-2.2.3.js:3187
self.fireWith @ jquery-2.2.3.js:3317
done @ jquery-2.2.3.js:8785
(anonymous function) @ jquery-2.2.3.js:9151

是什么导致了这些问题,我该如何解决?

最佳答案

错误原因:JSON.parse() 需要文本,但传递了对象。(感谢@Rayon)

由于数据已经是JSON格式了,所以没有必要在上面使用JSON.parse()

$.getJSON('us.json', function(data){

// Problem is here
$.each(JSON.parse(data), function(key, value) {

不解析数据

$.getJSON('us.json', function(data) {
$.each(data, function(key, value) {

对于第二个错误

Uncaught ReferenceError: html is not defined

在使用之前定义 html 变量。

var html = ''; // Add before `each`.

此外,不需要嵌套each,因为首先传入的数据each 已经是member 对象。这是使用 Array#forEach 编写的代码。

$.getJSON('us.json', function (data) {
var html = '';
data.forEach(function(member) {
html += '<div class="member">';
html += '<h4>' + member.firstname + ' ' + member.lastname + '</h2>';
html += '<p>' + 'has the following member number:' + member.studentnumber + '</p>';
html += '</div>';
});

$('#members').html(html);
});

关于javascript - 遍历 JSON 数组 : uncaught syntax error, Uncaught ReferenceError ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36881288/

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