簡體   English   中英

不能使用全局變量作為jQuery函數的參數

[英]Can not use global variable as argument for jQuery function

我正在嘗試使用API​​顯示當地天氣。 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;
}


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

我相信你遇到的問題是,在調用$.getJSON ,實際的api值仍設置為""

這很可能是由getCurrentPosition的異步操作引起的。 這意味着$.getJSONsetApi回調函數之前被有效地調用。

我建議根據您當前的代碼,最簡單的解決方案是在setApi函數中移動$.getJSON調用,這樣您就可以確保只正確設置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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM