2016-06-30 69 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當我調用該函數時,發生錯誤「未捕獲的參考錯誤:緯度未定義」。有沒有解決方案?我很抱歉,但我正處於學習階段。 –