2016-06-30 71 views
-2
var hhhhhhh = ''; 
     function displayLocation(latitude, longitude) { 
      var request = new XMLHttpRequest(); 

      var method = 'GET'; 
      var url = 'http://maps.googleapis.com/maps/api/geocode/json?latlng=' + latitude + ',' + longitude + '&sensor=true'; 
      var async = true; 

      request.open(method, url, async); 
      request.onreadystatechange = function() { 
       if (request.readyState == 4 && request.status == 200) { 
        var data = JSON.parse(request.responseText); 
        var addressComponents = data.results[0].address_components; 
        for (i = 3; i < 4; i++) { 
         hhhhhhh = addressComponents[i].long_name; 
        } 
       } 
      }; 
      request.send(); 
     } 
     console.log(hhhhhhh); 

var hhhhhhh没有从displayLocation函数中获取任何值。在控制台中,在函数内部函数之外,它的值为null。请Help.thank你jQuery全局变量值超出功能

+0

'的console.log(hhhhhhh形式)'是正确的后'VAR hhhhhhh形式执行= ''' 。您必须调用该函数,然后输出变量的值 – Roxoradev

回答

0

您拥有的console.log输出之前调用你的函数

var hhhhhhh = ''; 
 
function displayLocation(latitude, longitude) { 
 
    //your code 
 
    hhhhhhh = "Value"; 
 
} 
 
displayLocation(0, 0); 
 
console.log(hhhhhhh);

+0

感谢您的快速响应,先生。但仍然存在问题。现在,当我调用该函数时,发生错误“未捕获的参考错误:纬度未定义”。是否有解决方案?我很抱歉,但我正处于学习阶段。 –

+0

当您调用函数时,您可能没有正确传递经纬度值 – Roxoradev

0

你需要调用的函数,然后安慰值:

VAR HHHHHHH = ''; function displayLocation(latitude,longitude){ var request = new XMLHttpRequest();

  var method = 'GET'; 
      var url = 'http://maps.googleapis.com/maps/api/geocode/json?latlng=' + latitude + ',' + longitude + '&sensor=true'; 
      var async = true; 

      request.open(method, url, async); 
      request.onreadystatechange = function() { 
       if (request.readyState == 4 && request.status == 200) { 
        var data = JSON.parse(request.responseText); 
        var addressComponents = data.results[0].address_components; 
        for (i = 3; i < 4; i++) { 
         hhhhhhh = addressComponents[i].long_name; 
        } 
       } 
      }; 
      request.send(); 
     } 

    displayLocation(lat,long) // you need to call the function and then console the value 

     console.log(hhhhhhh); 
+0

感谢您的快速响应,先生。但仍然存在Problem.Now当我调用该函数时,发生错误“未捕获的参考错误:纬度未定义”。有没有解决方案?我很抱歉,但我正处于学习阶段。 –