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 の各関数で失われることです。その理由も解決方法もまだわかりません。Google は私が探している答えを教えてくれません。

編集 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で問題を再現してみてください。そこからお手伝いできます。

完全なソース コード

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

サーバー側からの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 に答える
0

json データがオブジェクトの配列である場合、itemには各オブジェクトが含まれるため、if()句でitem.actionを使用しますが、これは私の仮定にすぎません

于 2009-12-02T09:19:14.900 に答える