我在尝试从 success
回调中修改全局变量时遇到了 jQuery 问题:
<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>
我做错了什么?
最佳答案
这是因为在您执行警报时回调尚未完成。
Get 请求是异步的,因此即使尚未完成,也会继续执行。所以当alert()
语句执行时,success回调还没有执行,所以items
还是null。
您可以执行同步调用,也可以在成功回调中包含您尝试执行的任何操作。
关于javascript - jQuery AJAX 范围的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5085541/