JQuery $ .getJSON加载本地JSON文件不起作用

时间:2012-12-14 01:59:32

标签: jquery json getjson

我的问题非常简单,我有一个名为new.json的文件,我正在尝试使用JQuery来加载和显示数据。我一直在编写JavaScript代码:

$.getJSON("new.json", function(data){
        // I have placed alert here previously and realized it doesn't go into here
        $.each(data.streetCity, function(i,s){
            alert(s);
        });
    });
}

,new.json中的数据如下所示:

{"streetCity":
    {
        "1":"Abergement-Clemenciat",
        "2":"Abergement-de-Varey",
        "3":"Amareins"
    }
};

3 个答案:

答案 0 :(得分:11)

如果您使用的是Chrome。因为Chrome不允许xmlhttprequest请求本地文件。所以jquery无法加载你的new.json

你可以添加

- allow-file-access-from-files

到chrome的启动命令。这可以允许xmlhttprequest加载本地资源

答案 1 :(得分:2)

如果你使用的是jQuery 1.5+,你可以将错误处理程序链接到调用上,看看发生了什么:

$.getJSON("new.json", function(data){
        // I have placed alert here previously and realized it doesn't go into here
        $.each(data.streetCity, function(i,s){
            alert(s);
        });
    }).error(function(jqXhr, textStatus, error) {
                alert("ERROR: " + textStatus + ", " + error);
    });

new.json可能与调用页面的路径不同。此外,如果您的代码段准确无误,则不需要脚本中的最后一个大括号或json中的最后一个分号。

答案 2 :(得分:1)

你的问题是';' JSON文件中的(分号)。 JSON响应不需要分号。删除你的例子应该工作正常!

相关问题