2011-02-23 112 views
1

我在尝试修改success回调中的全局变量时遇到了jQuery问题:jQuery AJAX范围的问题

<html> 
<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> 

我做错了什么?

回答

3

这是因为在执行警报时,回调没有完成。

Get请求是异步的,所以即使它还没有完成,执行也会继续。所以当alert()语句执行时,成功回调尚未执行,因此items仍为空。

您可以执行同步调用,也可以包含您在成功回调中尝试执行的任何操作。

+0

完美答案,谢谢! – gjb 2011-02-23 00:19:50