views:

49

answers:

2

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.

+2  A: 
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');
          }
        });
    }
}
Māris Kiseļovs
Just remember to accept the parameter coming in from the ajax call: `success: function(data) {`
peirix
+1  A: 

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]);
      }
    });
}
jAndy