JQuery/Ajax calls in a For Loop

后端 未结 4 1282
悲&欢浪女
悲&欢浪女 2021-01-03 08:55

Is it possible to put (\"xxxxx\").html(data) in a for loop where the \"xxxx\" variable changes each time?

I honestly feel like I\'ve tried everything. I

相关标签:
4条回答
  • 2021-01-03 09:08

    Well, you have at least two options: use a closure, or use forEach().

    Fiddle below, containing both. I would use the closure solution, to confuse the Java programmers, and I think that it's more elegant, and more fun.
    http://jsfiddle.net/kmiklas/79s8S/4/
    open console to view data

    First, set the id of each row sequentially, like so:

    <tr id="row1"></tr>
    <tr id="row2"></tr>
    ...
    <tr id="rowN"></tr>
    

    Then put your row id's into an array.

    var pointsArray = new Array(999); // whatever length here
    for (var i = pointsArray.length; i > -1; i--) {
        pointsArray[i] = 'row' + i;
    }
    

    CLOSURE SOLUTION:

    Now, when retrieving your AJAX data, create an immediate function, passing i every time. This will create a new scope for each callback:

    for (var i = pointsArray.length; i > -1; i--) {
        (function(j){
             $.ajax({
                 type: "POST",
                 url: "some.php",
             })
             .done(function( data_from_ajax_call ) {
                 $('#' + pointsArray[j]).html(data_from_ajax_call)
             });
        })(i);
    }
    

    forEach() SOLUTION:

    You may also use Array.prototype.forEach(), "The forEach() method executes a provided function once per array element."
    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach

    pointsArray.forEach(function(rowName) {
         $.ajax({
             type: "POST",
             url: "some.php",
         })
         .done(function( data_from_ajax_call ) {
            $('#' + rowName).html(data_from_ajax_call)
         });
    }
    

    I'm using jQuery for the AJAX calls. I didn't test them; you have to fiddle with your data_from_ajax_call variable. Maybe return a JSON object here.

    0 讨论(0)
  • 2021-01-03 09:14

    How about creating a #P i first then append to parent. Then change the html()?

    0 讨论(0)
  • 2021-01-03 09:16

    if you loop looks something like this:

    for(var i=0; i<10; i++){
       $.ajax({
        //
        success:function(data){
           $("#p" + i + "_points").html(data);
        }
       });
    }
    

    it will not work as i will end up being the last i value in the loop; You need something like below

    for(var i=0; i<10; i++){
       (function(index){
          $.ajax({
           //
           success:function(data){
              $("#p" + index + "_points").html(data);
           }
          });
       })(i);
    }
    

    The closure along with the passing of i will keep number value for that call.

    of course there will need to exist elements with ids 1-10 or whatever number you use so:

    <element id="p1_points">
    <element id="p2_points">
    <element id="p3_points">
    ...
    

    EDIT to account for JSONP callback:

    modify myCallback() to be:

    function myCallback(data,index)
    

    and use the index to make your "#p"+index+"_points" etc ids

    and then for the loop and ajax:

    //Keeps track of the callbacks
    //we will prepend 'jsonpCallbacks.' to the callback names
    window.jsonpCallbacks = {};
    
    for (var i = 0; i < thisweeksraiders.length; i++){
        (function(index){
          window.jsonpCallbacks["myCallback"+index] = function(data){
             myCallback(data,index);
          };
        })(i);
        $.ajax({
            "url":"http://us.battle.net/api/wow/character/aerie-peak/" + thisweeksraiders[i] + "?jsonp=jsonpCallbacks.myCallback"+i,
            "type":"GET",
            "data": { fields: "items, professions, talents, progression"},
            "dataType":"jsonp",
            "contentType":"application/json",
            "jsonpCallback":"jsonpCallbacks.myCallback"+i,
            "success":function(data1){
            }
        })
    }
    
    0 讨论(0)
  • 2021-01-03 09:26

    You should have a different callback each time, if you wish to target different entities.

    Checkout closures, when you are ready, until then try it this way: (Pseudo code)

    for(...) {
        loadData(i);
    }
    
    
    function loadData(i) {   
       var index = i; 
    
       $.ajax({
            url: "",
            success : function() {    
                   $("#p" + index + "_points").html(data_from_ajax_call);
            }
       });
    }
    
    0 讨论(0)
提交回复
热议问题