Pregunta

Tengo el siguiente código

function updateSliderContent(json) {  //<- json defined here is correct
   var screen_order = json.screen_order.split('_');
   jQuery.each(screen_order, function(i, item) {
      var screen_id = item;
      //at this point it is not, thus the function does not execute whatever is in the if blocks
      if (json[screen_id].action == 'add') {
         //doSomething  
      } else if (json[screen_id].action == 'remove') {
         //doSomthingElse
      };
   }
}

Mi problema es que de alguna manera, el valor de JSON (que es un objeto de una llamada AJAX) se pierde en el cada función de jQuery. Todavía no he descubierto por qué, ni cómo resolverlo. Google no me da la respuesta que busco.

Editar 1

Esta es la llamada real.

function updateSlider() {
   var screenOrder = '';
   jQuery('div#slider td').each(function(i, item) {
      screenOrder += this.abbr + '_';
   })
   var ajaxData = {
      sid: sid,
      story: story,
      date: theDate,
      screenOrder: screenOrder,
      mode: 'ajax_update_slider'
   };
   jQuery.ajax({
      data: ajaxData,
      dataType: 'json',
      success: function (json) {
         updateSliderContent(json);
      }
   });
   theDate = Math.round(new Date().getTime()/1000.0); //UNIX Timestamp
   sliderTimer = setTimeout('updateSlider();',15000);
};
¿Fue útil?

Solución

He intentado y fallado, para reproducir el problema en JS Bin:
http://jsbin.com/ereha (editable vía http://jsbin.com/ereha/edit )

El código que nos has demostrado hasta ahora parece estar perfectamente bien, así que el problema debe ser causado por alguna otra parte de su código o sistema. Todos estamos disparando en la oscuridad si no sabemos cuál es el problema.

Por favor, tratar de reproducir el problema en http://jsbin.com y le podemos ayudar desde allí.

Completo código fuente

index.html

<!doctype html>
<html lang="en">
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>http://stackoverflow.com/questions/1831384/javascript-variable-value-gets-lost-between-functions</title>
    <script type="text/javascript" src="http://getfirebug.com/releases/lite/1.2/firebug-lite-compressed.js"></script>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
    <script type="text/javascript">
      $.ajaxSetup({url: 'test.json'});

      function updateSliderContent(json) {  //<- json defined here is correct
        var screen_order = json.screen_order.split('_');
        jQuery.each(screen_order, function(i, item) {
          var screen_id = item;
          //at this point it is not, thus the function does not execute whatever is in the if blocks
          if (json[screen_id].action == 'add') {
            console.log(screen_id, 'action add');
          } else if (json[screen_id].action == 'remove') {
            console.log(screen_id, 'action remove');
          };
        });
      }

      function updateSlider() {
        var ajaxData = {};
        jQuery.ajax({
          data: ajaxData,
          dataType: 'json',
          success: function (json) {
            updateSliderContent(json);
          }
        });
        // theDate = Math.round(new Date().getTime()/1000.0); //UNIX Timestamp
        sliderTimer = setTimeout('updateSlider();',15000);
      };

      $(updateSlider);
    </script>
  </head>
  <body>
  </body>
</html>

test.json

{
  'screen_order': 'foo_bar_baz',
  'foo': {
    'action': 'add'
  },
  'bar': {
    'action': 'add'
  },
  'baz': {
    'action': 'remove'
  }
}

Otros consejos

No parece haber nada malo con el jQuery.each ya que no puede reproducir el problema.

        function alertName (json) {
            var a = new Array();
            a.push(1);
            a.push(2);

            jQuery.each(a, function(i, item) {
                alert(json[0].name);
                alert(json[1].name);
            });
        }

        var andre = { name: "André" }
        var joana = { name: "Joana" }

        var arrayOfJson = new Array();
        arrayOfJson.push(andre);
        arrayOfJson.push(joana);

        alertName(arrayOfJson);

Función alertName() funciona exactamente como debe ser. El parámetro JSON no se pierde dentro de la función jQuery.each

Parece ser un problema en su aplicación, algo que no nos estás diciendo acerca. Por favor trate de "comprimir" el problema a una muestra de trabajo como lo hice y mostrar nosotros para que podemos tratar en nuestra cuenta:)

¿Está seguro json es un objeto. Tal vez sea una cadena JSON-? Que debiera eval antes de su uso.
Si lo consigue a través de llamada $.ajax() no se olvide de añadir dataType:'json' como una opción ...

bandeja en el si () cláusula de usar item.action , porque si los datos JSON es una matriz de objetos, elemento contener cada objeto, pero esto es sólo mi suposición

Creo que debe asegurarse de que la función updateSliderContent que se llama después de la respuesta JSON desde el lado del servidor.

El código de abajo no debería funcionar:

    var json = {};

    $.getJSON("/url/", {}, function(data){
        json = data;
    });

    //we call our function before the server response
    //and the json will be just blank object
    updateSliderContent ( json );

Así que, por favor, eche un vistazo a su código, porque a veces hemos hecho algo así sin intención.

El siguiente código debería funcionar y el objeto JSON no debe estar en blanco si el servidor realmente la respuesta de los JSON correcta.

    $.getJSON("/url/", {}, function(json){
        //we call only after the response from server
        updateSliderContent ( json );
    });
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top