[英]Div text doesn't change to API property
我正在進行FCC前端認證,但我無法正確處理api:
$(document).ready(function() {
$.getJSON("http://ip-api.com/json/", function(data) {
var city = data.city;
lat = data.lat;
long = data.lon;
$("#long").text("The weather for " + city + " is:");
url = "https://api.forecast.io/forecast/b537d8225ba7eaa6a34d16afbae307c3/" + lat + "," + long;
$.getJSON(url, function(data) {
temp = data.currently;
$("#tmp").text("b");
});
$("#tmp").text(temp);
});
$("#tmp").text(temp);
});
但是,tmp不會將其文本更改為var temp,即使是《暗夜天氣預報》,我也可以看到我的回叫已收到,謝謝!
-修復了@Martin Gottweis建議您的CORS
問題。 (ip-api不需要回調,但是預測是)
-在您的預報getJSON函數內部,您檢索.currently
,但是它只是其中包含更多數據的對象,您必須指定所需的內容(例如.summary
)。
-從預測getJSON外部移動代碼,以便可以訪問temp
變量。
$(document).ready(function() {
$.getJSON("http://ip-api.com/json/", function(data) {
var city = data.city;
lat = data.lat;
long = data.lon;
$("#long").text("The weather for " + city + " is:");
url = "https://api.forecast.io/forecast/b537d8225ba7eaa6a34d16afbae307c3/" + lat + "," + long + "?callback=?";
$.getJSON(url, function(data) {
temp = data.currently.summary;
$("#tmp").text(temp);
});
});
});
問題在於@PatrickEvans提到的cors。 嘗試這種方式:
$(document).ready(function() {
$.getJSON("http://ip-api.com/json/?callback=?", function(data) {
console.log(data)
var city = data.city;
lat = data.lat;
long = data.lon;
$("#long").text("The weather for " + city + " is:");
url = "https://api.forecast.io/forecast/b537d8225ba7eaa6a34d16afbae307c3/?" + lat + "," + long + "&callback=?";
$.getJSON(url, function(data) {
var temp = data.currently;
$("#tmp").text("b");
});
$("#tmp").text(temp);
});
$("#tmp").text(temp);
});
另外,閱讀jsonp
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.