无法将JSON对象的属性分配给其他变量
问题描述:
我正在构建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.city
到city
,但只有当我给你city
分解到location
。如果我是console.log(city)
,它会将我的城市,即a.city
的值记录到控制台。所以我所做的就是将city
的值赋值给另一个变量location
。这可能是什么原因,这是行不通的?
答
由于您的代码调用信息的方式,您需要在这些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中放置代码。
您遇到与CORS相关的问题。除非网站明确允许,否则您无法直接从浏览器访问其API。 – Ouroborus
你得到一个'404',即URL不起作用。这就是它被打破的原因。 – varlogtim
@Ouroborus我能够使用他们的API而不必通过CORS重定向它。例如。如果我'console.log(a.lat)',我可以记录我的位置的纬度。 –