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



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

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

澄清 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();

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

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);
});

最新更新