Nested AJAX Calls
in first ajax call server returns a json string that is converted to js array. I want to run an ajax call for each element of array.
For example, first ajax call returns semester 1,2,3,4. Now i want to retrieve subjects for semester 1 and show them in a table, then retrieve subjects of semester 2 and show all subjects in a table and so on...
I wrote a code but it shows all subjects in last table. Can some one help me?
$.ajax(
{
type: "POST",
url: "returnSemesterNumbers",
data: "programId="+selectedprog,
success: function(data)
{
var semesters=$.parseJSON(data);
for(x in semesters)
{
semnum=semesters[x].semesterNumber;
alert(semnum);
$("#tables").append('<table id=table'+x+' style=float:left><tr><td>'+semnum+'</td></tr>');
$.ajax(
{
type: "POST",
url: "returnCourses",
data: "programId="+selectedprog+"&semNum="+semnum,
success: function(data1)
{
var courses=$.parseJSON(data1);
for(y in courses)
{
$("#table"+x).append('<tr><td>'+courses[y].title+'</td></tr>');
开发者_如何学Go }
}
});
$("#table"+x).append('</table>');
}
}
});
}
else
{
$("#tables").css('display','none');
}
});
The callback in your inner ajax call captures the x
variable by reference.
Since all of the callbacks run after the loop, they all get the current value of x
, which is the last element in the set.
You need to move the code in the loop into a separate function that takes x
as a parameter.
The scope of variable x
might also cause issues.
Instead of:
for(x in semesters)
try:
for(var x in semesters)
Which will declare x as a variable in the scope of your first success ajax function, rather than as a global that can be changed by any other code (including jQuery).
精彩评论