jQuery全局变量值超出功能

时间:2016-06-30 06:56:22

标签: jquery geolocation

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在函数内部获取其值。请帮助。谢谢你

2 个答案:

答案 0 :(得分:0)

您需要调用该函数,然后控制该值:

var hhhhhhh =&#39;&#39 ;;             function displayLocation(纬度,经度){                 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);

答案 1 :(得分:0)

您必须在console.log输出之前调用您的函数

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