JavaScript:变量值在函数之间丢失

发布于 2024-08-13 14:04:10 字数 1230 浏览 6 评论 0原文

我有以下代码

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

I have the following code

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

My problem is that somehow, the value of json (which is an object from an AJAX Call) gets lost in the each function of jquery. I have not yet found out why, nor how to solve it. Google does not give me the answer I am looking for.

Edit 1

Here is the actual call.

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

羁〃客ぐ 2024-08-20 14:04:10

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

到目前为止,您向我们展示的代码看起来完全没问题,因此问题一定是由其他原因引起的您的代码或系统的一部分。如果我们不知道问题出在哪里,我们都是在摸黑。

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

完整源代码

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

I've attempted, and failed, to reproduce your problem on JS Bin:
http://jsbin.com/ereha (editable via http://jsbin.com/ereha/edit)

The code you've shown us so far seems perfectly fine, so the problem must be caused by some other part of your code or system. We're all just shooting in the dark if we don't know what the issue is.

Please try and reproduce the problem on http://jsbin.com and we can help you from there.

Complete Source Code

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'
  }
}
谁许谁一生繁华 2024-08-20 14:04:10

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 函数中丢失

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

There seems to be nothing wrong with the jQuery.each as I can't reproduce your problem.

        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() function works exactly as it should. The json parameter isn't lost within jQuery.each function

It seems to be a problem on your implementation, something you're not telling us about. Please try to "compress" your issue to a working sample as I did and show us so that we can try in on our own :)

作妖 2024-08-20 14:04:10

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

Are you sure json is an object. Maybe its a json-string? Than you should eval it before use.
If you get it via $.ajax() call don't forget to add dataType:'json' as an option...

a√萤火虫的光℡ 2024-08-20 14:04:10

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

tray in the if() clause to use item.action, because if the json data is an array of objects, item will contain each object, but this is only my assumption

沐歌 2024-08-20 14:04:10

我认为你应该确保在服务器端的 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 );
    });

I think you should make sure the function updateSliderContent is called after the json response from the server side.

The code below shouldn't work:

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

So, please have a look at your code because sometimes we did something like that without intention.

The code below should work and the json object must not be blank if the server really response the correct json.

    $.getJSON("/url/", {}, function(json){
        //we call only after the response from server
        updateSliderContent ( json );
    });
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文