2016-12-05 123 views
0

我正在構建Weather App for FreeCodeCamp。這是link to my CodePen無法將JSON對象的屬性分配給其他變量

我從this API中抽取當前位置的詳細信息。我試圖從獲得的結果中分配對象屬性到其他變量,但我的網頁不斷崩潰。例如 -

var city; 
var location; 
$.getJSON("http://ip-api.com/json", function(a) { 
    city = a.city; 
    location = city; 
}); 

上面的代碼打破我的頁面在控制檯下面的錯誤 -

pen.js:14 GET http://s.codepen.io/boomerang/ec76a96f53a8031f8d1405309568a2711480895619856/Greenville 404 (Not Found) 

頁正常工作時,我給你a.citycity,但只有當我給你city分解到location。如果我是console.log(city),它會將我的城市,即a.city的值記錄到控制檯。所以我所做的就是將city的值賦值給另一個變量location。這可能是什麼原因,這是行不通的?

+1

您遇到與CORS相關的問題。除非網站明確允許,否則您無法直接從瀏覽器訪問其API。 – Ouroborus

+0

你得到一個'404',即URL不起作用。這就是它被打破的原因。 – varlogtim

+0

@Ouroborus我能夠使用他們的API而不必通過CORS重定向它。例如。如果我'console.log(a.lat)',我可以記錄我的位置的緯度。 –

回答

1

由於您的代碼調用信息的方式,您需要在這些getJSON方法中嵌套大量呼叫。 將它們分配給全局作用域變量並不意味着它們將在這些函數運行後被定義。

var temp; 
var latitude; 
var longitude; 
var city; 
var region; 
var country; 
var location2; 

$.getJSON("http://ip-api.com/json", function(a) { 
    latitude = a.lat; 
    longitude = a.lon; 
    city = a.city; 
    location2 = city; 

    var weatherURL = "http://api.openweathermap.org/data/2.5/station/find?lat=" + latitude + "&lon=" + longitude + "&cnt=1&apikey=[API-KEY]"; 

    $.getJSON(weatherURL, function(a) { 
    temp = a[0].last.main.temp; 
    var firstCelcius = Math.round(a[0].last.main.temp - 273.15); 
    $("#temp").html(firstCelcius); 

    $('body').on('click', '#c', function(e) { 
     var fahrenheit = Math.round(((temp - 273.15) * 9/5) + 32); 
     $("#temp").html(fahrenheit); 
     $("#c").html(" °F"); 
     $("#c").attr("id", "f"); 
    }); 
    $('body').on('click', '#f', function(e) { 
     var celcius = Math.round(temp - 273.15); 
     $("#temp").html(celcius); 
     $("#f").html(" °C"); 
     $("#f").attr("id", "c"); 
    }); 
    }); 
}); 

訪問變量location globaly它將訪問了全球範圍的window.location這會讓網址更改爲hostname/city時也是如此。

要使用api,但是您必須在codepen中運行代碼而不是,但是不要在iframe中放置代碼。

相關問題