代码之家  ›  专栏  ›  技术社区  ›  Adi Sembiring

在jquery中设置全局变量

  •  2
  • Adi Sembiring  · 技术社区  · 15 年前

    如何设置全局变量。

    $(document).ready(function() {
    
          $("a.action").click(function(event) {
                var tempResponse = "";
                $.get("", function(response){
                    tempResponse = response; 
                });
                alert("response " + tempResponse );
          }
    
           //todo use response to manipulate some data
    });
    

    我声明了globa变量 tempResponse . 我设置了get call back函数。

    tempResponse = response; 
    

    但当我试图提醒响应时,没有显示任何数据。我也尝试这个解决方案。我更改变量声明 成为 $.tempResponse 更改设置脚本 $.tempResponse = response;

    但这不起作用。

    为什么会这样?

    5 回复  |  直到 12 年前
        1
  •  2
  •   Darin Dimitrov    15 年前

    因为在实际设置变量之前调用警报。记住,当调用 $.get . 试试这个:

    $(document).ready(function() {
        $.get('/somescript.cgi', function(response){
            alert('response ' + response);
        });
    });
    
        2
  •  3
  •   Blazemonger    12 年前

    我相信在脚本顶部设置全局变量,然后将Ajax调用设置为async:false将完全满足需要。

    这样,在JavaScript尝试分配变量之前,Ajax就完成了。 另外,Ajax函数对我来说比使用.get更干净。

    tempResponse = null;
    $.ajax({
        url: 'whatever.cgi',
        async: false,
        dataType: 'json',
        data: { blank: null }
        success: function(data) {
             tempResponse = data.response;
        }
     }).error(function(){
        alert('Ajax failed')
     });
    
     alert(tempResponse);
    

    在返回“response”的脚本中,请确保其为JSON格式。在PHP中,我将把数据做成一个类似

    $json_data = array('response'=>$var_name_php_for_response_value);
    

    然后只回显所需的数据,如:

     json_encode($json_data);
    

    这将产生以下格式: { "response":"some response text" } 这是正确的JSON格式。

        3
  •  0
  •   Patrick    15 年前

    您只是在$.get之后立即调用警报,因此tempresponse尚未就绪。

        4
  •  0
  •   Erik    15 年前

    要使其工作:

    $(document).ready(function() {
        var tempResponse = "";
        $.get("", function(response){
            tempResponse = response; 
            alert("response " + tempResponse );
        });
    });
    

    注意,您的警报现在位于JSON回调函数中;在JSON查询完成之前,此函数不会执行。

        5
  •  0
  •   Reigel Gallarde    15 年前

    我的建议是您必须等待Ajax完成。 使用 ajaxComplete()

    如果你有:

    var tempResponse = "";
        $.get("ajax/test.html", function(response){
            tempResponse = response; 
    
        });
    

    你可以:

    $('.log').ajaxComplete(function(e, xhr, settings) {
      if (settings.url == 'ajax/test.html') {
        alert("response " + tempResponse );
        $(this).text('Triggered ajaxComplete handler.');
      }
    });