开发者

Problem with jQuery AJAX scope

I am having trouble with jQuery with trying to modify a global variable from within the success callback:

<html>
<开发者_StackOverflow;head>
<script type="text/javascript" src="javascript/jquery.min.js"></script>
<script type="text/javascript">

  // Define items in the global scope
  items = null;

  // Get items from XML for a given category ID
  function getItems(categoryID)
  {
    $.ajax({
      type: 'GET',
      url: 'items.xml',
      dataType: 'xml',
      success: function(xml){
        items = $(xml).find('category[id="'+categoryID+'"]').children().first();
        // This works (returns the name of the first item)
        alert( items.attr('name') );
      }
    });
  }
</script>
</head>

<body>
<script type="text/javascript">
  $(function(){
    getItems(1);

    // This doesn't work (returns null)
    alert( items.attr('name') );
  });
</script>
</body>

</html>

What am I doing wrong?


This is because the callback hasnt finished by the time you are executing the alert.

the Get request is asynchronous so execution continues even if it has not finished. So when the alert() statement executes, the success callback has not yet executed, therefore items is still null.

You can either do a synchronous call, or include whatever you are trying to do inside the success callback.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜