JQuery/Ajax calls in a For Loop

后端 未结 4 1281
悲&欢浪女
悲&欢浪女 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:

    
    
    ...
    
    

    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.

提交回复
热议问题