【问题标题】:Why cant i access window.variable in Javascript?为什么我不能在 Javascript 中访问 window.variable?
【发布时间】:2023-03-19 19:15:01
【问题描述】:

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

【问题讨论】:

  • 你应该在 post callbac 中做警报,这里它在 window.uris 是 feed 之前被调用
  • 你的 ajax 是异步的。如果您在$.post 回调中放置另一个警报,您会注意到它在当前警报之后 发出警报。

标签: javascript jquery global-variables scope


【解决方案1】:

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

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

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

【讨论】:

  • 我实现了一个睡眠函数 function sleep(ms) { var dt = new Date(); dt.setTime(dt.getTime() + ms); while (new Date().getTime()
  • @Blitzkr1eg 此时的睡眠功能远非最佳。如果您的请求由于某种原因需要更长的时间,会发生什么?在使用数据之前,将您的进一步逻辑放在回调函数中或从那里调用另一个函数以确保请求实际完成!
猜你喜欢
  • 2012-05-28
  • 1970-01-01
  • 2023-01-24
  • 1970-01-01
  • 2021-07-01
  • 2014-11-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多