jquery 执行行为

jquery execution behaviour

本文关键字:执行 jquery      更新时间:2024-06-24
$(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。谁能帮助我如何完成我需要的东西?

提前致谢

如前所述,Ajax 是异步的,这意味着您的 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/

假设您更正了代码中的语法错误(.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
});

然后,ready函数中语句的执行顺序是首先.each()将为每个'.out'元素调用$.ajax(),然后执行最后的console.log('2')并完成ready函数,然后按照浏览器接收Ajax响应的顺序为每个Ajax请求调用成功函数 - 这不一定与Ajax相同提出了要求。(显然,这假设他们实际上是成功的。

这是因为 Ajax 请求(应该是(异步的 - 响应回调将始终在当前代码块完成后调用,无论接收响应的速度有多快,因为(忽略 Web 工作者(JavaScript 不是多线程的。