bobbyjones
bobbyjones

Reputation: 2079

problems fetching a simple JSON data via getJSON

im getting crazy over this. doenst seem to work after a following a tutorial very closely.

can you please take a look at my code. i just want to print a JSON data at my <ul> element

my index page

...
<body>
  <ul>
  </ul>
<div id="foo">
    <script language="javascript" type="text/javascript" src="js/jquery.js"></script>
    <script language="javascript" type="text/javascript" src="js/custom.js"></script>
</div>
</body>
...

my custom.js

$(document).ready (function () {
    $.getJSON("json_data.json", function(data) {
        $.each(data.emp, function() {
            $("ul").append("<li>test:" + this['name'] + "</li><li>" + this['last'] + "</li>");
        });
    });
});

my json_data.json

{
    "emp": [
        { "name" : "bob", "last": "marley" },
        { "name" : "kurt", "last": "cobain" }
    ]
}

what am i missing here? checking at my chrome developers tools > Network i get status for jquery.js and custom.js 304 not modified

i dont know if this affects why my fetching JSON wont work.

Upvotes: 0

Views: 143

Answers (1)

rach
rach

Reputation: 679

Please check the fiddle provided in the comment.

var jsonString = {"emp": [{ "name": "bob", "last": "marley" },{ "name": "kurt", "last": "cobain" }]};

    $.each(jsonString.emp, function (key, value) {
        alert(jsonString.emp[key]["name"] + jsonString.emp[key]["last"]);
         $("ul").append("<li>" + jsonString.emp[key]["name"] + " " + jsonString.emp[key]["last"] + "</li>");
        console.log(key, value);

    });

It seems you need the key and value. Key is the index and value is respected value for object. I hope it works for you.

Upvotes: 1

Related Questions