简体   繁体   中英

jQuery.get() Variables Scope

I'm working with jQuery's Ajax but in my case I need to store the response in global variables:

var points = Array()
$.get("/data", {"id": 1}, function(data) {
    for (var i=0; i < data.length; i++) {
        points[data[i].someid] = data[i];
    }
alert(points[22].someid.toString()); // it works fine
});

alert(points[22].someid.toString()); // undefined

However when I try to access the variable points outside of the scope of $.get() I just get an undefined object. But I get the right object inside $.get().

What's the best way/standard to manage context and scope in this case?

Your scope is fine, but the $.get() runs asynchronously. It starts the call then immediately executes the second alert. When the $.get() completes, it executes the function(data){} . Whatever you were going to use out of that, you need to do in there. If you go to firebug console after all this is over, you should find that alert(points[22].someid.toString()) has what you expect.


You can disable elements in your code to discourage further user action:

var points = Array();

// prevent further user action
$('#actionButton').attr('disabled', true);
// optionally show a loading.gif to let them know the browser is busy

$.get("/data", {"id": 1}, function(data) {
    for (var i=0; i < data.length; i++) {
        points[data[i].someid] = data[i];
    }
    alert(points[22].someid.toString()); // it works fine

    // process points data

    // hide loading.gif
    // re-enable user action
    $('#actionButton').removeAttr('disabled');
});

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