I am trying to get my $.getJSON to work but it returns nothing. Here is my jQuery:
$('#courseSelect').bind('change', function()
{
data = $.getJSON('lessons.js');
var html ='<select name="lessonSelect id="lessonSelect">';
var len = data.length;
alert(data.length); //this alerts "undefined"
for (var i = 0; i< len; i++) {
html += '<option value="' + data[i].value + '">' + data[i].name + '</option>';
}
html +='</select>';
alert(html); //this alerts <select...></select>
//but no option tags because there's nothing to loop through
$('lessonsDiv').html(html);
});
This is my lessons.js file
{"lessons":
[
{"value": "1", "name": "Lesson 1"},
{"value": "2", "name": "Lesson 2"},
{"value": "3", "name": "Three"}
]
}
Ultimately, what I’m trying to do is create a new select list of lessons when a course first is selected. But for now, I’m just trying to get this getJSON method to work but it’s not. Be great if anyone can see what’s wrong with. Is it expecting a different sort of data?
The call to
getJSON()is asynchonrous; the result is not available immediately. What is returned fromgetJSON()is thejqXHRobject which is monitoring the state of the asynchoronous request.You need to register a callback (which is what the second parameter is for), which is executed after the response is available. The
jqXHRobject which is handling the asynchronous request will execute your callback automatically once the request has completed successfully.Once you’ve done this,
datawould be an object such as;So you’d actually need to use
data.lessonsto access the array you’ve got (anddata.lessons.lengthto retrieve the length of it).