为什么我不能访问Javascript中的window.variable?

为什么我不能访问Javascript中的window.variable?,javascript,jquery,global-variables,scope,Javascript,Jquery,Global Variables,Scope,我在任何函数之外声明windows.uris, 然后,我在$.each()中添加元素,在最后一行中,当通知window.uris为空时。 为什么? window.uris=new Array(); window.groups=新数组(); jQuery(文档).ready(函数($){ host=document.location.host, 路径=document.location.pathname; url=主机+路径; var domg=新对象(); var-optgroup; var p

我在任何函数之外声明windows.uris, 然后,我在$.each()中添加元素,在最后一行中,当通知window.uris为空时。 为什么?

window.uris=new Array();
window.groups=新数组();
jQuery(文档).ready(函数($){
host=document.location.host,
路径=document.location.pathname;
url=主机+路径;
var domg=新对象();
var-optgroup;
var productsDom=“”;
if(包含(url,'manage/items.php')){
$.post($)http://localhost/frontaccounting/proxy.php',
{
“url”:”http://localhost:8081/stock/categories/",
“m”:“get”,
“数据”:”
},
功能(数据){
d=$.parseXML(数据);
$xml=$(d);
$xml.find(“category”)。每个(
功能(即,e){
optgroup='';
categoryId=$(e).children(“id”).text();
auxx=(类别ID*1);
window.uris[i]=”http://localhost:8081/stock/categories/“+(auxx);
window.groups[auxx+“”]=optgroup;
}
);
}
);  
//睡眠(2000年);
警报('URI'+window.uris);

在函数中对某个url进行异步调用。但是,
警报
命令位于函数内部,而不是回调内部

因此,它将被立即调用,而不是等待AJAX请求完成并且数据出现


一个简单的解决方案是将您的
警报
移动到回调函数中。

您应该在post callbac中执行警报,在这里它在窗口之前被调用。uris是feedYour ajax是异步的。如果您在
$.post
回调中放置另一个警报,您会注意到它在当前警报之后被发出警报。我实现了一个sleep函数sleep(ms){var dt=new Date();dt.setTime(dt.getTime()+ms);while(new Date().getTime()window.uris = new Array(); window.groups = new Array(); jQuery(document).ready(function($) { host = document.location.host, path = document.location.pathname; url = host + path; var domg = new Object(); var optgroup; var productsDom = ""; if (contains(url, 'manage/items.php')) { $.post('http://localhost/frontaccounting/proxy.php', { "url":"http://localhost:8081/stock/categories/", "m":"get", "data": "" }, function (data) { d = $.parseXML(data); $xml = $( d ); $xml.find("category").each( function (i,e) { optgroup = '<optgroup label="'+ $(e).children("name").text()+'">'; categoryId = $(e).children("id").text(); auxx = (categoryId*1); window.uris[i]="http://localhost:8081/stock/categories/" + (auxx ); window.groups[auxx + ""] = optgroup; } ); } ); //sleep(2000); alert('URI' + window.uris);