简体   繁体   中英

Global Variable - AJAX jQuery

I'm trying to set the global variable countryCode . But the value is always null. What can I do? I tried many ways. PLS HELP!

function GetGeolocation(){

  $.getJSON("http://ip-api.com/json/?callback=?",function(data){
  $.each(data, function(k, v) {
    table_body += "<tr><td>" + k + ": " + "</td><td><b>" + v + "</b></td></tr>";

      if (k == "countryCode")
      {
          SetGeolocation(v);
      }
    })             
  }); 
}

function SetGeolocation(value){

  countryCode = value;
  console.log(countryCode); //Value
}

function Result(){
  console.log(countyCode); //Null
}

$(document).ready(function(){
  GetGeolocation();
  Result();
});

In JavaScript, a variable which has been declared without var keyword inside a function becomes global only after function's call.

Consider this:

function foo(){
    bar = 123;
}

// Reference error - bar is undefined
console.log(bar);

Now before testing bar variable, let's call the foo function.

function foo(){
    bar = 123;
}

foo();

// 123
console.log(bar);

You got it? Right? Good. As for your code, the error is pretty obvious countryCode is undefined just because you didn't call SetGeolocation() before. To make it work as you expect you need somehow call SetGeolocation() before you call Result() .

But don't do this seriously. Global variables is well-known what not to do thing. Consider passing a variable as a dependency instead

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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