javascript - JSON + jQuery 不工作

标签 javascript jquery html json

我正在尝试让 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/

相关文章:

javascript - 存储属于不同选项卡的文本区域的状态

php - jQuery 不在选择上加载数据

javascript - 为什么此代码在 jsfiddle 中不起作用

jquery - <a> 的下载属性的替代实现

javascript - 表格单元格悬停和行跨度

html - 在不影响body宽度的情况下使用宽背景div的技巧

javascript - 密码对比

javascript - XPath 表达式中的 Protractor Javascript 传递参数

javascript - jQuery:选择器不适用于 ajax 加载的内容

javascript - 如何使用 .get() 函数将从 XML 读取的值存储到本地对象的成员