为什么我无法在Javascript中访问window.variable?

时间:2012-05-14 11:27:24

标签: javascript jquery global-variables scope

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

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);

1 个答案:

答案 0 :(得分:2)

在您的函数中,您对某个网址进行异步调用。但是,alert命令位于您的函数内部,而不是在回调中。

因此,它会被立即调用,而不是等到AJAX请求完成并且您的数据存在。

一个简单的解决方案是在回调函数中移动alert

相关问题