I ask the help of binding in the serial binding of ajax requests. (The example below does not work correctly). The correct sequence is 1-2-3-4.

HTML:

<div id="1" data-loader="../components/header.html"></div> <div id="2" data-loader="../components/navigation.html"></div> <div id="3" data-loader="../components/body.html"></div> <div id="4" data-loader="../components/footer.html"></div> 

Js:

 <script> var url; var id; var j=1; $(document).ready(function () { $('div[data-loader]').each(function() { url=$(this).attr("data-loader"); id=$(this).attr("id"); $.get(url, function(data){ $('#'+j).html(data); j++; }); }); }); 

  • And how wrong? - 0xdb
  • you need synchronic execution - make a synchronous request .... but ajax was created not to be synchronous - Alexey Shimansky

1 answer 1

The problem is that the code inside $.get will be executed after all each . Because It is not known in advance in which order the answers will come, then it is impossible to predict in advance the value of j in each request.

In order for it to be consecutive $('#'+1) , $('#'+2) , $('#'+3) , you need to save the value j where the thread in the local closure inside each (so that each call each keeps your j )

This is how it should work:

 var url; var id; var j=1; $(document).ready(function () { $('div[data-loader]').each(function() { url=$(this).attr("data-loader"); id=$(this).attr("id"); var tmp_j = j++; $.get(url, function(data){ $('#'+tmp_j).html(data); }); }); }); 
  • Thank you very much. This is the correct answer. - Denis V