Pass a variable to a function from inside an ajax call

后端 未结 2 615
鱼传尺愫
鱼传尺愫 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 22:45

    your are directly executing the method and passing its result as the callback for the success callback.

    the xhr is already passed as the 3rd argument so try

    success: function(nn,status, xhr) {
                $('#host_'+nn).append("last modified: " + xhr.getResponseHeader("Last-Modified"));
            }
    

    if you have to pass the nodename as well, the you need to use a function that returns a function

    success: (function(nn){
                  return function(data ,status, xhr) {
                     // you can use nodename here...
                     $('#host_'+nn).append("last modified: " + xhr.getResponseHeader("Last-Modified"));
                };
            })(nodename)
    
    0 讨论(0)
  • 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 +='<a href="'+node_json+'" target="_blank" id="host_'+nodename+'">data</a>';
    
        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
         ...
    });
    
    0 讨论(0)
提交回复
热议问题