3

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"
    }
};
Explosion Pills
  • 188,624
  • 52
  • 326
  • 405
yi2ng2
  • 141
  • 2
  • 5
  • 14
  • Make sure that `new.json` is in the same directory as the file that is running the JS that makes the ajax request. I'm pretty sure you don't want the `;` either. – Explosion Pills Dec 14 '12 at 02:06
  • if not running server on local machine, some browsers won't allow ajax without adjusting settings – charlietfl Dec 14 '12 at 02:10
  • Possible duplicate, if you're using Chrome: http://stackoverflow.com/questions/2541949/problems-with-jquery-getjson-using-local-files-in-chrome – apsillers Dec 14 '12 at 02:33
  • the interesting part is that it doesn't effect only Chrome but other browsers as well – yi2ng2 Dec 25 '12 at 07:43

3 Answers3

11

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

Junnan Wang
  • 627
  • 4
  • 12
  • 1
    I was doing another application and reminds me for the issue. I have tried and yes it's working now, thanks. – yi2ng2 Jan 19 '13 at 18:08
2

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.

mr.freeze
  • 13,731
  • 5
  • 36
  • 42
1

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

Shaunak
  • 17,377
  • 5
  • 53
  • 84