2012-08-01 35 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