2016-10-19 26 views
0

私はjquery各関数を持っています。その中に関数を呼び出しています。この関数は前の要素に対してこの関数が完了している場合にのみ呼び出されます。アヤックスを使用してそれを行うにはjquery内の関数をそれぞれ呼び出す

function x(t){ 
    var a = something; 

    $.each(a, function(index,value){ 
     y(this); 
    }); 
} 

function y(t){ 
    $.ajax({ 

    }).done(function(r){ 
     if(r.success){     
        } 
     else{ 
     } 

    }); 

    // This function should be called for the second element 
    // in the each function only if its completed for the first element. 
} 
+5

そして、なぜそれが完全ではないでしょうか?それは非同期ですか? – adeneo

答えて

5

$.each(内部非同期アクションがない限り、y(this)を呼び出し、実行を含む)現在のものが行われているときに次の反復でのみ発生し、同期機能である



再帰を使用してループの模倣を使用します。

var currentIndex = 0; 

function x(t) { 
    if (currentIndex >= something.length) { 
     return; 
    } 

    $.ajax({ 
     url: '', 
     data: something[currentIndex], 
     success: function() { 
      currentIndex++; 

      x(t); 
     } 
    }); 
} 
+0

私はy関数の中でajaxを呼び出しています。したがって、ajaxが完了したら、それをチェックする必要があります。 –

+0

@SandeepKollabathula - これはあなたが質問に追加すべきはずの情報です。 – adeneo

+0

@adeneo申し訳ありませんが、私は自分のコードを編集して、次の時から明白であることを確認します –

0

としては、項目2がy機能が何かを実行しているという事実を、それがすでに項目1.ここ

だと例によって行うの到着が、それ以外の場合に他の人が、この関数は、同期的に実行し、その上で述べました非同期ですが、それを指定していませんでしたか?

function x(t){ 
 
    var a = ["one", "two", "tree"]; 
 

 
    $.each(a, function(index,value){ 
 
     y(this, index); 
 
    }); 
 
} 
 

 
function y(t, index){ 
 
    // This function should be called for the second element 
 
    // in the each function only if its completed for the first element. 
 
    console.log(index + " "+ t +" => running in y") 
 
} 
 
x("")
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

関連する問題