简体   繁体   中英

Why cant i access window.variable in Javascript?

I am declaring windows.uris outside any function, then i'm adding elements in $.each(), at the last line when alerting window.uris is empty. Why ?

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

In your function you make an asynchronous call to some url. The alert command, however, is inside your function and not inside the callback.

So it will be called immediatly instead of waiting until the AJAX-request has finished and your data is present.

A simple solution is to move your alert inside the callback-function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM