简体   繁体   English

jQuery.get()变量范围

[英]jQuery.get() Variables Scope

I'm working with jQuery's Ajax but in my case I need to store the response in global variables: 我正在使用jQuery的Ajax,但就我而言,我需要将响应存储在全局变量中:

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. 但是,当我尝试访问$ .get()范围之外的变量点时,只会得到一个未定义的对象。 But I get the right object inside $.get(). 但是我在$ .get()中得到了正确的对象。

What's the best way/standard to manage context and scope in this case? 在这种情况下,管理上下文和范围的最佳方法/标准是什么?

Your scope is fine, but the $.get() runs asynchronously. 您的范围很好,但是$.get()异步运行。 It starts the call then immediately executes the second alert. 它启动呼叫,然后立即执行第二个警报。 When the $.get() completes, it executes the function(data){} . $.get()完成后,它将执行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. 如果所有这些都结束后转到Firebug控制台,则应该发现alert(points[22].someid.toString())符合您的期望。


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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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