Javascript - 范围问题 - 有很好的Javascript答案

时间:2014-12-19 18:02:39

标签: javascript scope

我正在尝试在getLocation()中使用ajax响应来保存变量lat和long以便在getWeatherReport()中使用,但是当我在第二个函数中控制它们时,两个变量都是空字符串。

据我所知,创建函数范围之外的变量将允许它们由第一个函数更新,然后将这些更新的值插入第二个函数。如果有人能解释我哪里出错了,为什么不是这种情况,我将非常感激。谢谢!

澄清AJAX调用工作正常。

console.log(lat + ", " + long); Shows the expected results of a latitude and longitude.

JS

var lat = "";
var long = "";

function getLocation(){
    console.log("Getting location with ajax");
    if(window.XMLHttpRequest){
        var xhr = new XMLHttpRequest();
        xhr.addEventListener("load", function(){
            console.log("loading...");
            console.log(xhr.responseText);
            var response = JSON.parse(xhr.responseText);
            console.log("Parsed response: ");

            var lat  = response.latitude;
            var long = response.longitude;

            console.log(lat + ", " + long);

            return lat;
        }, false);

        xhr.addEventListener("error", function(err){
            console.log("Could not complete the request");
        }, false);

        xhr.open("GET", "http://www.telize.com/geoip", true);
        xhr.send();
        console.log("Requestiong location info...");
    } else {
        console.log("Unable to fetch location info from dropbox.");
    }
}

function getWeatherReport(){
    console.log("Weather Report Location");
    console.log(lat + long);
}

getLocation();
getWeatherReport();

1 个答案:

答案 0 :(得分:2)

这是因为你在这里重新定义它们:

var lat  = response.latitude;
var long = response.longitude;

删除var个关键字,您应该没问题。

更新

尝试修改您的代码:

var latitude = "";
var longitude = "";

function getLocation(callback){
    console.log("Getting location with ajax");
    if(window.XMLHttpRequest){
        var xhr = new XMLHttpRequest();
        xhr.addEventListener("load", function(){
            console.log("loading...");
            console.log(xhr.responseText);
            var response = JSON.parse(xhr.responseText);
            console.log("Parsed response: ");         

            callback(response);

        }, false);

        xhr.addEventListener("error", function(err){
            console.log("Could not complete the request");
        }, false);

        xhr.open("GET", "http://www.telize.com/geoip", true);
        xhr.send();
        console.log("Requestiong location info...");
    } else {
        console.log("Unable to fetch location info from dropbox.");
    }
}  

getLocation(function(response) {
    console.log("Weather Report Location");

    latitude  = response.latitude;
    longitude = response.longitude;

    console.log(latitude + ", " + longitude);
});