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

标签 javascript jquery global-variables scope

我在任何函数之外声明 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/

相关文章:

jquery - 使用 jQuery .each() 时函数什么时候执行?

javascript - JQuery 插件,Javascript - 如何仅为 JQuery 插件全局变量或 json 对象创建并在函数级别更改此(变量、对象)

python - 在python中跨文件设置全局变量

python - 如何从 Python 3 的函数内更新全局变量?

Javascript : Uncaught InvalidStateError: Failed to read the 'selectionDirection'

javascript - 如何使用 JQuery ajax 调用从 JSON 获取某些数据?

javascript - 如何获取 px 维度的 <div> 高度

javascript - 如何正确观察变化

javascript - 从 PHP 访问 POST 字符串

javascript - 地址簿 jQuery 支持