-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。有人可以帮我完成我需要的吗?

提前致谢

4

2 回答 2

1

Assuming you corrected the syntax errors in your code (missing $ before .ajax, missing " on url value, and missing closing }); on the $.ajax call, plus any other errors I didn't spot):

$(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
});

Then the order the statements within your ready function will be executed is first the .each() will call $.ajax() for each of the '.out' elements, then the console.log('2') at the end will be executed and the ready function will complete, then later the success function will be called for each Ajax request in the order the Ajax responses are received by the browser - which isn't necessarily the same order the Ajax requests were made. (Obviously this assumes they actually are successful.)

This is because Ajax requests are (supposed to be) asynchronous - the response callbacks will always be called after the current block of code finishes, regardless of how fast the response is received, because (ignoring web workers) JavaScript is not multi-threaded.

于 2012-08-01T04:46:06.937 回答
1

如前所述,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/

于 2012-08-01T03:25:06.113 回答