2012-08-01 31 views
-2
$(document).ready(function() { 
    $('.out').each(function(index) { 
     .ajax({      
      url: "php, 
      type: "GET", 
      success: function(data) { 
      // LOOP each dynamic textbox for my specific validation 
     console.log('1'); // flag if any error 
     } 
    }); 

    // I though this will run after $('.out').each() 
    console.log('2'); // my plan is to check if atleast 1 error occur 
}); 

result: 
> 2 
> 1 
> 1 
> 1 

instead of: 
> 1 
> 1 
> 1 
> 2 

我认为这个流程是先运行每个函数先显示1 1 1等,然后它会显示2.任何人都可以帮助我如何完成我所需要的?jquery执行行为

在此先感谢

+1

你到底需要什么? – 2012-08-01 02:58:09

+1

无法复制,我得到'1 1 1 2'。 – Musa 2012-08-01 02:58:45

+0

哦对不起,我忘了一些东西,我已经添加了我的ajax,然后把console.log(1)放在ajax里面。也许ajax有一些延迟,脚本不会等待ajax完成。我不确定 – Paengski 2012-08-01 03:01:22

回答

1

正如已经提到的,阿贾克斯是异步的,这意味着被称为成功的功能之前,你的console.log(“2”)语句可以被执行。

尝试是这样的:

$(document).ready(function() { 
    $('.out').each(function(index) { 
     $.ajax({      
      url: "yourUrl.php", 
      type: "GET", 
      success: function(data) { 
       // LOOP each dynamic textbox for my specific validation 
       console.log('1'); // flag if any error 
      }, 
      complete: function (jqXHR, textStatus){ 
       //This will be be called when the request finishes 
       //(after success and error callbacks are executed) 
       console.log('2'); // my plan is to check if atleast 1 error occur 
      } 
     }); 
    }); 
}); 

看看这里,以更好地了解了jQuery的AJAX调用: http://api.jquery.com/jQuery.ajax/

+0

谢谢,这使我很开心 – Paengski 2012-08-02 00:43:59

1

假设你在你的代码纠正语法错误(.ajax前失踪$,失踪",url值,而关闭});关于$.ajax打电话,加上其他任何我没有发现的错误):

$(document).ready(function() { 
    $('.out').each(function(index) { 
     $.ajax({      
      url: "php", 
      type: "GET", 
      success: function(data) { 
      // LOOP each dynamic textbox for my specific validation 
      console.log('1'); // flag if any error 
      } 
     }); 
    }); 

    console.log('2'); // my plan is to check if atleast 1 error occur 
}); 

然后您准备函数中的语句将被执行的顺序是先.each()将调用$.ajax()每个'.out'元素,那么console.log('2')在年底将被执行,并且准备好,可以完成,然后后面的将按照浏览器接收Ajax响应的顺序为每个Ajax请求调用成功函数 - 这不一定与Ajax请求的顺序相同。 (显然,这个假定他们实际上成功。)

这是因为Ajax请求(应该是)异步 - 当前代码块结束后的反应回调总是会被调用,不管有多快收到的响应,因为(忽略网络工作者)JavaScript不是多线程的。

+0

谢谢,这使我很开心。 – Paengski 2012-08-02 00:43:47