【问题标题】:JSON + jQuery not workingJSON + jQuery 不工作
【发布时间】:2011-04-23 07:59:27
【问题描述】:

当按下按钮时,我正在尝试让 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 没有检测到错误。我重写了几次代码,寻找错误,将其与类似的代码进行比较等等,但找不到任何东西。

提前致谢!

【问题讨论】:

    标签: javascript jquery html json


    【解决方案1】:

    你的 json 符号是错误的

    使用: 而不是=,例如:

    ..........
    "images" : [
        { "source" : "images1", "alternative" : "altImg1" },
        ....................
    ]
    ..........
    

    【讨论】:

    • 哦,我是多么愚蠢...非常感谢!
    • 我猜 jQuery 优雅地隐藏了错误。尝试使用 json 验证器找出未来的小错误 jsonlint.com ;)
    • 是的,因此我不喜欢 Web 开发(以及您需要编写的代码量)。再次感谢!
    猜你喜欢
    • 2012-01-07
    • 2012-01-14
    • 2011-01-31
    • 1970-01-01
    • 2011-11-24
    • 1970-01-01
    • 1970-01-01
    • 2016-05-13
    • 1970-01-01
    相关资源
    最近更新 更多