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"
    }
};
4
  • 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. Commented Dec 14, 2012 at 2:06
  • if not running server on local machine, some browsers won't allow ajax without adjusting settings Commented Dec 14, 2012 at 2:10
  • Possible duplicate, if you're using Chrome: stackoverflow.com/questions/2541949/… Commented Dec 14, 2012 at 2:33
  • the interesting part is that it doesn't effect only Chrome but other browsers as well Commented Dec 25, 2012 at 7:43

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

1 Comment

I was doing another application and reminds me for the issue. I have tried and yes it's working now, thanks.
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.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.