【问题标题】:Can not use global variable as argument for jQuery function不能使用全局变量作为 jQuery 函数的参数
【发布时间】:2017-01-20 21:25:10
【问题描述】:

我正在尝试使用 API 显示当地天气。 API url 根据用户的本地位置生成。

var lat,lon = null;
var key = "mykey";
var api = "";

function setApi(position){
 lat = Math.round(position.coords.latitude*1000)/1000;   
 lon = Math.round(position.coords.longitude*1000)/1000;

 api = "http://api.openweathermap.org/data/2.5/weather?lat=" + lat + "&lon=" + lon + "&appid=" + key;
}


navigator.geolocation.getCurrentPosition(setApi);

$.getJSON(api, function(data){
  console.log(data.sys.country);
});

如果我使用我的 api 全局变量作为 $.getJSON 函数的参数,问题就不会发生。如果我改用字符串,它会起作用。例如:

  $.getJSON("http://api.openweathermap.org/data/2.5/weather?lat=46.295&lon=30.648&appid=%mykey%", function(data){
console.log(data.sys.country);
});

【问题讨论】:

  • 所以我想说api 不是您在通话时认为的那样。我猜它仍然是""。例如,可能getCurrentPosition 失败..(或者可能是异步的..我不熟悉)
  • getCurrentPosition 没有失败。我可以通过控制台访问我的 api var,它具有正确的价值。我猜异步可能是问题所在。谢谢。
  • 尝试在设置 api 值之后将调用移至然后,如果你确定它可以达到那么远
  • 你是对的,它现在可以工作了。非常感谢。

标签: javascript jquery


【解决方案1】:

我相信您遇到的问题是,在调用$.getJSON 时,实际的api 值仍设置为""

这可能是由 getCurrentPosition 中的异步操作引起的。这意味着$.getJSONsetApi 回调函数之前被有效地调用。

我建议根据您当前的代码,最简单的解决方案是将 $.getJSON 调用移动到您的 setApi 函数中,这样您就可以确定它仅在 之后调用> api 值已正确设置。

例如:

var lat,lon = null;
var key = "mykey";
var api = "";

function setApi(position){
    lat = Math.round(position.coords.latitude*1000)/1000;   
    lon = Math.round(position.coords.longitude*1000)/1000;

    api = "http://api.openweathermap.org/data/2.5/weather?lat=" + lat + "&lon=" + lon + "&appid=" + key;

    $.getJSON(api, function(data){
        console.log(data.sys.country);
    });
}

navigator.geolocation.getCurrentPosition(setApi);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-03-02
    • 2020-10-28
    • 2022-09-25
    • 1970-01-01
    • 1970-01-01
    • 2011-02-14
    • 1970-01-01
    相关资源
    最近更新 更多