Extra parameter for jQuery's ajax success func

2019-06-21 04:44发布

问题:

I'm fetching an XML file using this code:

function getMaps(){

    toLoad = loadMaps.length;

    for (var i = 0; i < loadMaps.length; i++){
        $.ajax({
          type: "GET",
          url: loadMaps[i],
          dataType: "xml",
          success: processMap
        });
    }
}

Which works fine, but I want to give processMap another parameter (namely loadMaps[i], the name under which to store the loaded xml)

I can't figure out how to do this without resorting to global variables, which is not what I want.

回答1:

The jQuery success callback has three parameters, which cannot be changed or expanded. So you need to call your function within an anonymous function which closes over.

for (var i = 0; i < loadMaps.length; i++){
    $.ajax({
      type: "GET",
      url: loadMaps[i],
      dataType: "xml",
      success: function(xhr, textStatus, error){
           processMap(loadMaps[i]);
      }
    });
}


回答2:

function getMaps(){
    toLoad = loadMaps.length;

    for (var i = 0; i < loadMaps.length; i++){
        $.ajax({
          type: "GET",
          url: loadMaps[i],
          dataType: "xml",
          success: function() {
              // do anything
              processMap(x,y,z,'foo');
          }
        });
    }
}


回答3:

The problem of accepted issue that "i" will be always with the last value in the loop, at least the Success event happens faster than next iteration of a loop, which is almost never happens.

Here is how it worked in my case:

function getMaps(){

    toLoad = loadMaps.length;

    for (var i = 0; i < loadMaps.length; i++){
        $.ajax({
          type: "GET",
          url: loadMaps[i],
          dataType: "xml",
          success: (function(loadMap){
              return function processMap(response){
                // code of processMap function ...
                alert(loadMap);
              }
          })(loadMaps[i])
        });
    }
}

Here is the original answer of similar question: how to pass multiple arguments to onSuccess function in Prototype?