2

我有以下代码

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

我的问题是,不知何故,json 的值(它是来自 AJAX 调用的对象)在 jquery 的每个函数中丢失了。我还没有找到原因,也不知道如何解决它。谷歌没有给我我正在寻找的答案。

编辑 1

这是实际的调用。

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

5 回答 5

2

我试图在 JS Bin 上重现您的问题,但失败了:http:
//jsbin.com/ereha(可通过http://jsbin.com/ereha/edit编辑)

到目前为止,您向我们展示的代码看起来非常好,因此问题一定是由您的代码或系统的其他部分引起的。如果我们不知道问题是什么,我们都只是在黑暗中拍摄。

请尝试在http://jsbin.com上重现该问题,我们可以从那里为您提供帮助。

完整的源代码

索引.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>

测试.json

{
  'screen_order': 'foo_bar_baz',
  'foo': {
    'action': 'add'
  },
  'bar': {
    'action': 'add'
  },
  'baz': {
    'action': 'remove'
  }
}
于 2009-12-03T04:36:43.883 回答
1

jQuery.each 似乎没有任何问题,因为我无法重现您的问题。

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

alertName()功能完全按照它应该的方式工作。json 参数不会在jQuery.each函数中丢失

这似乎是您的实施中的一个问题,您没有告诉我们。请尝试像我一样将您的问题“压缩”为一个工作示例并向我们展示,以便我们自己尝试:)

于 2009-12-02T10:41:02.727 回答
0

你确定json是一个对象。也许它是一个json字符串?比你应该eval在使用前。
如果您通过$.ajax()电话获得它,请不要忘记添加dataType:'json'为选项...

于 2009-12-02T08:59:13.013 回答
0

if()子句中的托盘使用item.action,因为如果 json 数据是一个对象数组,item将包含每个对象,但这只是我的假设

于 2009-12-02T09:19:14.900 回答
0

我认为您应该确保在服务器端的 json 响应之后调用函数updateSliderContent 。

下面的代码不应该工作:

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

因此,请查看您的代码,因为有时我们会无意中做了类似的事情。

如果服务器确实响应了正确的 json,则下面的代码应该可以工作,并且 json 对象不能为空。

    $.getJSON("/url/", {}, function(json){
        //we call only after the response from server
        updateSliderContent ( json );
    });
于 2009-12-02T14:26:16.113 回答