繁体   English   中英

声明全局变量不起作用(返回未定义)

[英]Declaring global variable not working (returning undefined)

我已经进行了基本设置,而我的问题是我的函数load_heat2 locations_map变量。 我在下面指出了未定义的位置:

//declare global variables

var full_map;
var locations_map;

function callIndex() {
    $(document).ready(function() {
 //call some functions
        load_map();
        load_test_map2();
        super_test_map();
        load_heat2(); 
    });

  $.ajax({
      url: 'php/get_map_tables.php',
      type: 'POST',
      dataType: 'JSON',
       data: {
          client_id: client_id, //defined elsewhere
      },
        success: function(data) { //this gives me the correct data in the right variables
            var locations_map = data[0].locations_map;
            var full_map = data[0].full_map;
        }
});
function load_heat2(){
       console.log(locations_map); //this yields undefined
}

} //end of callIndex function

我试图避免将所有内容包装在AJAX /成功函数中,所以我需要全局变量才能正常工作。

谢谢。

您在成功声明中声明了一个名为locations_map的局部变量

 $.ajax({
  url: 'php/get_map_tables.php',
  type: 'POST',
  dataType: 'JSON',
   data: {
      client_id: client_id, //defined elsewhere
  },
    success: function(data) { //this gives me the correct data in the right variables
        **var** locations_map = data[0].locations_map;
        var full_map = data[0].full_map;
    }

您正在ajax函数中重新声明两个变量。

var full_map;
var locations_map;

这是将它们声明为全局,但是当您在此处设置它们时

success: function(data) { //this gives me the correct data in the right variables
      var locations_map = data[0].locations_map;
      var full_map = data[0].full_map;
}

它成为本地的。 为了使它们保持全球性,您需要删除

var

所以看起来像

success: function(data) { //this gives me the correct data in the right variables
    locations_map = data[0].locations_map;
    full_map = data[0].full_map;
}

获得ajax请求的响应后,调用load_heat2()函数。 同样,像其他答案所指出的那样,删除两个变量的“ var”。

  //declare global variables

var full_map;
var locations_map;

function load_heat2(){
       console.log(locations_map); //this yields undefined
}
function callIndex() {
    $(document).ready(function() {
 //call some functions
        load_map();
        load_test_map2();
        super_test_map();
    });

  $.ajax({
      url: 'php/get_map_tables.php',
      type: 'POST',
      dataType: 'JSON',
       data: {
          client_id: client_id, //defined elsewhere
      },
        success: function(data) { //this gives me the correct data in the right variables
            locations_map = data[0].locations_map;
            full_map = data[0].full_map;
            load_heat2();
        }
});


} //end of callIndex function

暂无
暂无

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

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