简体   繁体   English

jQuery回调不使用全局变量

[英]jquery callback not using global variable

I have a small script that gets the location from geoplugin... i want to store the returned co-ords in a variable i have declared globally... but for some reason the callback wont read it. 我有一个从geoplugin获取位置的小脚本...我想将返回的坐标存储在我已全局声明的变量中...但是由于某种原因,回调函数不会读取它。 How do i make the callback use the global variable? 如何使回调使用全局变量?

if(navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(function(position) {
        myLocation = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
    }, function() {
        noLocation();
    },{timeout: 20});
}
else if (google.gears) {
    var geo = google.gears.factory.create('beta.geolocation');
    geo.getCurrentPosition(function(position) {
        myLocation = new google.maps.LatLng(position.latitude,position.longitude);
    }, function() {
        noLocation();
    });
}
else {
    noLocation();
}
function noLocation() {
$.getJSON("http://www.geoplugin.net/json.gp?id=117.201.92.17&jsoncallback=?",
    function(data) {
        if (data != "" && data.geoplugin_latitude != "")
            myLocation =  new google.maps.LatLng(data.geoplugin_latitude, data.geoplugin_longitude)
        else
            myLocation = new google.maps.LatLng()
    });

} }

For some reason i think its because of the asynchronous call... Can i get over the issue some how? 由于某种原因,我认为这是由于异步调用引起的...我可以通过一些方法解决问题吗?

It looks like it is storing it in the global variable "myLocation". 看起来它正在将其存储在全局变量“ myLocation”中。 However, it's likely that you are attempting to read the value before it has actually been set. 但是,您可能试图在实际设置该值之前先读取该值。 The way an asynchronous call works is that it returns immediately, then sometime in the future, it will call the callback function if and when the request gets a response. 异步调用的工作方式是立即返回,然后在将来的某个时间,如果请求获得响应,它将调用回调函数。 The rest of your code will continue to run in the meantime. 您的其余代码将在此期间继续运行。

Try an "alert" after the assignment to myLocation to see if it is being populated: 在分配给myLocation之后尝试“警报”,以查看是否正在填充:

myLocation =  new google.maps.LatLng(data.geoplugin_latitude, data.geoplugin_longitude)
alert(myLocation)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM