Pregunta

I am trying to pull down xml content from the server using jQuery.post() in a for loop on an list of multiple document names. Only the last response is being stored in the associative-array successfully while the other entries end up undefined.

var pagedata  = new Array () ;

loadpagexml = function ( liststring ) {
  var pagenames = liststring.split(',') ;

  for ( var i in pagenames ){
    xmltoget = pagenames[i]+'.xml' ;
    $.post( xmltoget , function(data) { 
      pagedata[ pagenames[i] ] = data ;
    }) ;
  }
}

var listofpages = 'poo,dung,corn' ;
loadpagexml ( listofpages )

>pagedata['poo']
  undefined
>pagedata['dung']
  undefined
>pagedata['corn']
  #document
¿Fue útil?

Solución

You're suffering from a closure problem with your callback, so the captured value is always the last one form the loop, particularly because this is an async operation.

You should be able to do this:

(function(id, url)
{
    var idInternal = id;
    $.post(url, function(data)
    {
       pagedata[pagenames[idInternal]] = data;
    });
})(i, $xmlToGet);
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top