全局变量不起作用

时间:2012-08-25 05:56:12

标签: javascript jquery

我一直在用头撞墙。有人可以告诉我我做错了吗?

var foo = 100;

function loadData() {
   // this pops up a window that says it's 100
   alert(foo);  

   $.getJSON(myvars.constants.ajaxpath + "getsettings", function(data) {
      foo = 200;
      // this pops up a window that says it's 200
      alert(foo);
   });
   // this pops up a window that says it's 100
   alert(foo); 
}

我将全局变量设置为getJSON()调用内的任何值仅在getJSON()调用中有效。函数退出后,全局变量将恢复为之前的值。

如何在getJSON()调用中设置此全局变量?我也尝试过使用.success(),. complete()等。我希望它保持设置为200,而不是恢复为100。

谢谢!

P.S。显然我在getJSON()调用中使用全局变量做其他事情,但简单的变量设置是为了说明问题。

4 个答案:

答案 0 :(得分:1)

您...

foo = 200
一旦ajax请求返回,就会调用

....所以这是“最后一个”alert(foo)之后。 完成此脚本的执行后,如果您弹出开放式控制台(F12)并输入foo,则应该看到200。

答案 1 :(得分:1)

变量被设置回来,第三个也是最后一个alert在集合之前被简单地调用。

因为您正在使用异步JSON调用,所以执行不是线性的。在大多数情况下,该代码将类似于:

var foo = 100;

function loadData() {
   // this pops up a window that says it's 100
   alert(foo);  

   // The call is sent at this point
   $.getJSON(myvars.constants.ajaxpath + "getsettings");

   // this pops up a window that says it's 100
   alert(foo); 
}

// Some time later, after the server responds, this function is actually run

function(data) {
   foo = 200;
   // this pops up a window that says it's 200
   alert(foo);
});

您可以通过在调用返回后调用alert或显示foo,或者将JSON调用设置为同步来强制执行,这将强制执行按预期进行(但实践很糟糕)。

答案 2 :(得分:0)

在此设置成功事件的回调,并在成功完成ajax请求时调用此回调。

$.getJSON(myvars.constants.ajaxpath + "getsettings", function(data) {
  foo = 200;
  alert(foo);
});

警告foo的最后一行是先前执行的。因此,在ajax reqest之后,你的变量将是200。

答案 3 :(得分:0)

试试这个

var foo = 100;

function loadData() {

   alert(foo);  
   $.ajax({
      async: false,
      url: myvars.constants.ajaxpath + "getsettings",
      dataType: "json",
      success: function(data) {
      foo = 200;
      alert(foo);
   }
 });
  alert(foo); 
} 
相关问题