JQuery $.getJSON load local JSON file not working

2020-02-06 04:03发布

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:

$.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:

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

3条回答
Emotional °昔
2楼-- · 2020-02-06 04:35

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

查看更多
做自己的国王
3楼-- · 2020-02-06 04:37

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

you can add

--allow-file-access-from-files

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

查看更多
男人必须洒脱
4楼-- · 2020-02-06 04:40

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

$.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.

查看更多
登录 后发表回答