简体   繁体   中英

Recursive javascript/ajax function: unable to access global variable set inside function

In my ajax application I'm trying to use a recursive function inside of which another function is called which creates a global variable, and I want to use that variable inside the recursive function. However, I'm running into trouble because I can't access that global variable inside the recursive function (although it is available if I call that function on its own). The code for the recursive function is below.

ajaxCity.displayCell() sets a window.cells[] variable, which contains an array of numbers. The idea is to call the tree() function for each of those numbers.

function tree (topCell) {
    var ajaxCity = new Ajax();  
    ajaxCity.displayCell(topCell);

    for (var i = 0; i < window.cells[topCell].cKids.length; i++) {
        tree(window.cells[topCell].cKids[i]);
    }
}

The window.cells[] variable is available after I run the function once, but how should I change the process so that it works the way I'm imagining?

Thanks for your help!

edit: here's the error that I get.

TypeError: window.cells[topCell] is undefined

if I call the tree function again, it will work for one "level" deeper, then give the error again, etc

================

Thank you James Montagne, as you pointed out, the problem is that I need to wait for the ajax request to come back. Thanks again!

I'm making some assumptions here based on variable names, but I take it that

ajaxCity.displayCell(topCell);

will make an ajax call, the result of which will be the creation of window.cells... .

If this is the case, the problem is that AJAX is asynchronous (That's the first A). If you make an AJAX request and then immediately try to use the result of that request, you will not find a result. This is because the AJAX request has not yet returned. You will need to instead work with the result in the callback of the AJAX request.

window.cells=new Array();

在全球范围内。

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