我正在尝试让 jQuery 在按下按钮时获取 JSON 文件并将其中的数据放在一个简单的站点上。 因此,JSON 代码如下所示:
{
"images" : [
{ "source" = "images1", "alternative" = "altImg1" },
{ "source" = "images2", "alternative" = "altImg2" },
{ "source" = "images3", "alternative" = "altImg3" }
]
}
以及 HTML + jQuery:
<html xmlns="http://www.w3.org/1999/xhtml">
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<head>
<title>jQuery</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
</head>
<body>
<button>Press Me!</button>
<script>
$('button').click(function() {
$.getJSON('json-db.html', function(data) {
for(var i = 0; i < data.images.length; i++) {
var image = data.images[i];
$('#result').append('<h1>' + image.source + ' ' + image.alternative + '</h1>');
}
});
});
</script>
<div id="result">Result</div>
</body>
</html>
Firebug 没有检测到任何错误。我多次重写代码,寻找错误,将其与类似代码进行比较等等,但找不到任何东西。
提前致谢!
最佳答案
你的json符号是错误的
使用 :
而不是 =
,例如:
..........
"images" : [
{ "source" : "images1", "alternative" : "altImg1" },
....................
]
..........
关于javascript - JSON + jQuery 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5763036/