javascript - Parsing Facebook graph API JSON to html -
i'm new json , trying return list of facebook albums:
$(document).ready(function () { $.getjson("https://graph.facebook.com/me/photos?fields=id,name&access_token=my token", function (data) { var items = []; $.each(data, function (key, val) { items.push("<li id='" + key + "'>" + val + "</li>"); }); $("<ul/>", { "class": "my-new-list", html: items.join("") }).appendto(".results"); }); });
json facebook:
{ "data": [ { "id": "10150589771916817", "name": "mobile uploads", "created_time": "2012-03-03t14:47:48+0000" }, { "id": "41633726816", "name": "old pics", "created_time": "2008-08-18t21:44:29+0000" } ], "paging": { "cursors": { "after": "nde2mzm3mjy4mty=", "before": "mtaxnta1odk3nze5mty4mtc=" } } }
[object object]
gets returned each item in html. doing wrong?
firstly response has array named data
, need loop on data.data
.
secondly, in example key
integer index of iteration , value
whole object within array. need access properties of array explicitly. try this:
// retrieved json data... var data = { "data": [{ "id": "10150589771916817", "name": "mobile uploads", "created_time": "2012-03-03t14:47:48+0000" }, { "id": "41633726816", "name": "old pics", "created_time": "2008-08-18t21:44:29+0000" }], "paging": { "cursors": { "after": "nde2mzm3mjy4mty=", "before": "mtaxnta1odk3nze5mty4mtc=" } } } // inside ajax request callback... var items = []; $.each(data.data, function (i, obj) { items.push('<li id="' + obj.id + '">' + obj.name + '</li>'); }); $('<ul/>', { 'class': 'my-new-list' }).append(items).appendto('.results');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script> <div class="results"></div>
Comments
Post a Comment