嵌套的AJAX调用 [英] Nested AJAX Calls

查看:88
本文介绍了嵌套的AJAX调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

返回一个json字符串,该字符串将转换为js数组.我想为数组的每个元素运行一个ajax调用.

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.

例如,第一个ajax调用返回第1、2、3、4个学期.现在我想检索第一学期的主题并将其显示在表格中,然后检索第二学期的主题并将其显示在表格中,依此类推...

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>');
                                    }
                               }
                             });
                    $("#table"+x).append('</table>');
                    }
               }
             });
            }
            else
            {
                $("#tables").css('display','none');
            }
});

推荐答案

内部ajax调用中的回调通过引用捕获x变量.

The callback in your inner ajax call captures the x variable by reference.

由于所有回调都在循环之后运行,因此它们都将获得当前值x,它是集合中的最后一个元素.

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.

您需要将循环中的代码移动到一个单独的函数中,该函数以x作为参数.

You need to move the code in the loop into a separate function that takes x as a parameter.

这篇关于嵌套的AJAX调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆