我用Ajax调用服务器返回了一个json字符串,该字符串被转换为js数组。现在我想对数组的每个元素运行Ajax调用。
例如,第一次Ajax调用返回学期1、2、3、4。现在我想检索第一学期的主题并在表中显示它们,然后检索第二学期的主题,并在表中显示所有的主题等等…….
我写了一个代码,但它显示了最后一个表中的所有主题。有人能帮我解决这个问题吗?
$.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>');
}
}
});
$("#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).