Pass a variable to a function from inside an ajax call

后端 未结 2 616
鱼传尺愫
鱼传尺愫 2021-01-25 22:34

I tried to use this loop to read some urls to read their modified time:

var arr = [];

//... fill arr with push

for (var e in arr) {
        nodename=arr[e].hos         


        
2条回答
  •  不思量自难忘°
    2021-01-25 23:03

    If arr is truly an array, just use .forEach or even better .map (with a shim on older browsers) to encapsulate each iteration's scope without the need for additional closures:

    var xhrs = arr.map(function(e) {
        var nodename = e.hostname;
        var node_json = "/nodes/" + nodename;
    
        html +='data';
    
        return $.ajax({
            url: node_json
        }).done(function(data, status, xhr) {
            $('#host_'+nodename).append("last modified: " + xhr.getResponseHeader("Last-Modified"));
        });
    });
    

    The reason to use var xhrs = arr.map() instead of .forEach is that you then (for free) get the ability to call yet another callback once every AJAX request has completed:

    $.when.apply($, xhrs).then(function() {
         // woot!  They all finished
         ...
    });
    

提交回复
热议问题