I\'m using Jquery mobile, so ignore some of the following overdone css, its not related to the core issue.
I\'m having a problem looping over the \"Places\" in my JSON p
You are using getJSON
and each
the wrong way:
function loadJSON(){
$.getJSON("http://localhost:8000/api/0.1/tonight-mobile.json&callback=?", callback);
}
function callback(data){
var target = $("#tonight-list");
$.each(data.Places, function(i) {
target.append("...");
});
}
You have to pass a reference of the callback function do getJSON
, not call the function.
If you do $("#tonight-list").each()
then you are iterating over the elements selected by the selector. This function takes only one argument (the callback) anyway. See the documentation.
You want $.each() which takes an array as first and a callback as second argument.
each()
doesn't work that way. It takes a set of elements on the page, and loops over them, calling a function for each one. In this case, you are looping over $("#tonight-list")
, which will only have one item in it (IDs are supposed to uniquely identify one element in a document).
What you seem to want to do is to loop over the data (not the #tonight-list
element), and add the data to that element, right? In that case, you want normal JavaScript to do the loop, something like this:
var list = $("#tonight-list");
for (var i=0, place; place=data.Places[i]; ++i) {
list.append("<li role='option' tabindex='" + i + "'>" + place.name + "</li> ...etc);
}
Note that I have no idea if you are loading trusted data that is meant to contain HTML, untrusted plain text, etc. You may need to encode the data before inserting it or (better) insert it structurally instead of concatenating strings, depending on your use-case.