0

I have the following HTML code in a file called test.html. Both the HTML file and the JSON file below are stored on a server within the same directory.

<!DOCTYPE html>
<html>
<head>
<title>Shape Up</title>
<meta name="robots" content="noindex,follow">
<meta name="description" content="">
<meta name="keywords" content="">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script language="JavaScript" type="text/javascript">
function ajax_get_json()
{
    var hr = new XMLHttpRequest();
    hr.open("GET", "game.json", true);
    hr.setRequestHeader("Content-type", "application/json", true);
    hr.onreadystatechange = function()
    {
        if(hr.readyState == 4 && hr.status == 200)
        {
            var data = JSON.parse(hr.responseText);
            var results = document.getElementById("results");
            results.innerHTML = "";
            for(var obj in data)
            {
                results.innerHTML += data[obj].title;
            }
        }
    }
    hr.send(null);
    results.innerHTML = "requesting...";
}
</script>
</head>
<body>
<div id="results"></div>
<script language="JavaScript" type="text/javascript">
ajax_get_json();
</script>
</body>
</html>

It pulls data from a file called game.json which is stored in the same directory.

{
    "level_001":
    {
        "id":001,
        "title":"Level 1",
        "difficulty":0,
        "comments":"this is how you complete level 1"
    },
    "level_002":
    {
        "id":002,
        "title":"Level 2",
        "difficulty":0,
        "comments":"this is how you complete level 2"
    }
}

The problem is that the results.innerHTML = ""; line is never reached. Why?

There are no errors in the browser, I've checked this on Firefox and on Safari.

3
  • 1
    Do you get any errors in the browser's console? Commented Nov 28, 2013 at 12:08
  • Check if you allow local XMLHttpRequests! Commented Nov 28, 2013 at 12:13
  • No errors, and the files are stored on a server. (not local) Commented Nov 28, 2013 at 12:14

1 Answer 1

3

According to jsonlint.com your JSON is invalid because of these properties:

"id":001
...
"id":002

You need to either remove the leading zeros:

"id":1

or make the numbers strings:

"id":"001"

For further details see the format rules spelled out at json.org

Presumably the line you mentioned is never reached because JSON.parse() gives an error about the above. (Do you not see an error in the browser's console?)

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

1 Comment

Thank you, that was it. I'll accept the answer after 5 mins as per request of SO.

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.