我在任何函数之外声明 windows.uris, 然后,当警报 window.uris 为空时,我在 $.each() 的最后一行添加元素。 为什么?
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);
最佳答案
在您的函数中,您对某个网址进行异步调用。但是,alert
命令位于您的函数内部,而不是位于回调内部。
因此它将立即被调用,而不是等到 AJAX 请求完成并且您的数据存在。
一个简单的解决方案是将您的警报
移动到回调函数内。
关于javascript - 为什么我无法在 Javascript 中访问 window.variable?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10582405/