开发者

Extra parameter for jQuery's ajax success function

I'm fetching an XML file using this code:

func开发者_开发百科tion 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.


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


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');
          }
        });
    }
}


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?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜