jQuery.get()变量范围 [英] jQuery.get() Variables Scope

查看:86
本文介绍了jQuery.get()变量范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用jQuery的Ajax,但在我的情况下,我需要将响应存储在全局变量中:

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

但是当我尝试访问$ .get范围之外的变量点时(我只是得到一个未定义的对象。但是我在$ .get()中得到了正确的对象。

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?

推荐答案

您的范围很好,但 $。get()以异步方式运行。它启动呼叫然后立即执行第二个警报。当 $。get()完成时,它会执行函数(数据){} 。无论你打算用什么,你都需要在那里做。如果你在完成所有这些之后去firebug控制台,你会发现 alert(points [22] .someid.toString())有你所期望的。

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

这篇关于jQuery.get()变量范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆