2011-11-07 43 views
0

我想在我的ajax响应中访问变量“维度”,但无法获取它。我不想让这个变量全局。以下是我的代码
javascript中的范围变量,jquery

$(document).ready(function(){ 
    $('#submittext').click(function(){ 
    var dimensions; 
    $.ajax({ 
    type: "GET", 
    url: "bin/getcontentsize.php", 
    data: findContentsize, 
    success: function(response){ 
     //want to access dimensions here to assign response and some calculation(but not able to access it) 
    } 
    }); 
    //so i can use here 
    }); 
    }); 
+0

你是什么意思,你不能访问它?它会产生一个错误,错误的值等... – JaredPar

+8

你应该可以很好地访问尺寸。然而,它将会是'未定义'的,因为你从未初始化它。 – samjudson

+0

@samjudson是的,它说没有定义 –

回答

7

在这种情况下,您可以访问dimensions变量从ajax回调和代码立即在ajax请求开始之后。这两个上下文都可以访问该变量。

什么是最有可能导致问题,虽然是时机。在ajax请求完成后,success方法将异步运行。最好将其视为稍后执行。但紧接在$.ajax调用之后的代码将立即执行。因此,当它运行时,dimensions变量上的success处理程序不会看到任何影响。

如果您想要运行的代码的值为dimensions,如success方法所计算的,您需要从success回调中调用该代码。例如

$('#submittext').click(function(){ 

    var handleNewDimensions = function (dimensions) { 
    // Code that used to be after the $.ajax line 
    } 

    $.ajax({ 
    type: "GET", 
    url: "bin/getcontentsize.php", 
    data: findContentsize, 
    success: function(response){ 
     var dimensions = doTheCalculation(...); 

     // Call the code which needs to deal with the new dimensions 
     handleNewDimensions(dimensions); 
    } 
    }); 
+0

谢谢你,这是我的问题的解决方案谢谢。谢谢 –

1

分配维度变量的值,并再次测试:

var dimensions="sample"; 
1

这应该工作:

$(document).ready(function(){ 
    $('#submittext').click(function(){ 
    var dimensions = 1; 
    $.ajax({ 
    type: "GET", 
    url: "bin/getcontentsize.php", 
    data: findContentsize, 
    success: function(response){ 
     alert(dimensions); 
    } 
    }); 
    //so i can use here 
    }); 
    }); 
2

运行它时出现问题。

$(document).ready(function(){ 
    $('#submittext').click(function(){ 
     var dimensions="1"; 
     $.ajax({ 
      type: "GET", 
      url: "bin/getcontentsize.php", 
      data: findContentsize, 
      success: function(response){ 
       dimensions = "2"; 
      } 
     }); 
     //!!!!Attention 
     alert(dimensions); // result is "1", not "2" 
    }); 
}); 

首先,您的代码已经运行。之后,您的$ .ajax开始运行。