如何同步两个嵌套的jquery foreach循环?

时间:2015-12-14 11:40:24

标签: jquery ajax

我在内循环的最后一次迭代中为每个循环嵌套了两个,我想调用一个包含ajax调用的jquery函数。只有在从这个ajax调用获得结果之后,才会发生下一次外部迭代。有没有办法同步这些循环。

$.ajax({
        type: "POST",
        contentType: 'application/json;charset=utf-8',
        dataType:'json',
        url: 'getCall1',
        data: JSON.stringify(send_data),
        success: function(json)
        {
          $.each(json,function(i,item){
            $.ajax({
                    type: "POST",
                    contentType: 'application/json;charset=utf-8',
                    dataType:'json',
                    url: 'getcall2',
                    data: JSON.stringify(send_data),
                    success: function(json)
                    {
                      $.each(json,function(i,item){
                       //For last iteration of this loop i want to call a function contain another ajax call. After completion of this call i want to continue with next iteration of outer loop
                        callFun();
                      });
                    }
             });
      });
   }

});

function callFun(){
  $.ajax({
        type: "POST",
        contentType: 'application/json;charset=utf-8',
        dataType:'json',
        url: 'getcall3',
        data: JSON.stringify(send_data),
        success: function(json)
        {

        }
  });
}

2 个答案:

答案 0 :(得分:0)

您可以使用回调函数处理它:

console.log

祝你好运

答案 1 :(得分:-1)

您可以使用jQuery promises或deferred Object,它们最适合您的问题。确保所有这些Ajax都是异步的。请尝试这样:

<bean id="properties" class="org.apache.camel.component.properties.PropertiesComponent">
    <property name="location" value="classpath:myproperties.properties" />
</bean>