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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13871625/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 13:02:36  来源:igfitidea点击:

JQuery $.getJSON load local JSON file not working

jqueryjsongetjson

提问by yi2ng2

My problem is very simple, I have a file with the name of new.json and I am trying to use JQuery to load and display the data. I have been writing JavaScript code:

我的问题很简单,我有一个名为 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);
        });
    });
}

and the data in new.json looks as below:

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

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

回答by Junnan Wang

If you are using Chrome. Because Chrome don't allow xmlhttprequest to request local file. So jquery can not load your new.json

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

you can add

你可以加

--allow-file-access-from-files

--allow-file-access-from-files

to the start command of chrome. This can allow xmlhttprequest to load local resource

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

回答by mr.freeze

If you are using jQuery 1.5+ you can chain an error handler onto the call to see what is going on:

如果您使用的是 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 is probably in a different path than the calling page. Also, if your snippets are accurate you don't need that last curly brace in the script or the last semicolon in the json.

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

回答by Shaunak

Your problem is the ';' (semicolon) in the JSON file. JSON response doesn't need a semicolon. Remove that your example should work fine!

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