Frantumn
Frantumn

Reputation: 1764

Load external JSON file

I can't seem to get JSON when it's from an external file. When I write it inline, it works fine. But when I created a file called test.json and copied the JSON in to it, I never get the contents.

Here's my HTML and JavaScript. I should note that both HTML and JSON files are within the same folder.

What am I doing wrong?

<!DOCTYPE html>
<html>
    <head>
        <title>JSON Sandbox</title>
    </head>
    <body>
        <h2>JSON Sandbox</h2>

        <p id="demo"></p>

        <script type="text/javascript">
            var text = $.getJSON({
                dataType : "json",
                url : "test.json",
                data : data,
                success : window.alert("JSON Aquired.")

            });

            var obj = JSON.parse(text);
            document.getElementById("demo").innerHTML = obj.name + "<br>" + obj.street + "<br>" + obj.phone;
        </script>

    </body>
</html>

Here's my test.json file

{
    "name":"John Johnson",
    "street":"Oslo West 1",
    "phone":"111 1234567"
}

Upvotes: 0

Views: 5679

Answers (2)

user2400931
user2400931

Reputation:

Change the file extension to js. and change the html file as below:

<!DOCTYPE html>
<html>
    <head>
        <title>JSON Sandbox</title>
        <script src="jquery-1.8.2.min.js"></script>
    </head>
    <body>
        <h2>JSON Sandbox</h2>

        <p id="demo"></p>

        <script type="text/javascript">
            var obj = new Object();
            var error = new Object();
            $.getJSON('test.js').done(function (data) {
                obj = data;
                document.getElementById("demo").innerHTML = obj.name + "<br>" + obj.street + "<br>" + obj.phone;
            }).error(function (err) {
                error = err;
            });

        </script>
    </body>
</html>

Upvotes: 2

Cerbrus
Cerbrus

Reputation: 72839

Your success handler is defined incorrectly.

Replace:

success : window.alert("JSON Aquired.")

With:

success : function(data){
    window.alert("JSON Aquired.")
    // `data` is the returned object:
    document.getElementById("demo").innerHTML = data.name + "<br>" + data.street + "<br>" + data.phone;
}

You need to do what you want to do with the data, in the success handler, because $.getJSON is an AJAX call, which means it's asynchronous.

Upvotes: 0

Related Questions