在构建天气应用程序时,我遇到了问题。它必须自动检测我们所在的位置,并提供适当的温度和位置,例如城市名称。我试图用来自JSON的数据替换p。特别是我试图用城市名称替换段落。由于某种原因,它不起作用。
http://codepen.io/ekilja01/full/KaMXjp/
这是我的 HTML :
<body>
<div class="container-fluid">
<i class="fa fa-thermometer-empty fa-2x" aria-hidden="true"></i>
<br><br><br>
<form>
<input type="radio" name="celsiusOrFahrenheit" value="fahrenheit"> Fahrenheit °F;<br>
<input type="radio" name="celsiusOrFahrenheit" value="celsius" checked> Celsius °C<br>
</form>
<div class="yourlocation">
<h1>Your location is: </h1>
<p class="yourLocationGoesHere">
</p>
</div>
<h1>Your current weather is: </h1>
<div class="showTemperature">
<p class="showDegree">32</p>
</div>
</div>
</body>
这是我的 jQuery :
$(document).ready(function(){
$.getJSON("http://api.openweathermap.org/data/2.5/weather? q=London,uk&appid=7f5806c8f3fd28b03e2d6580a50732d6", function (data){
var len = data.length;
var html = "";
html += "<p>'" + len.name + "'</p>";
$(".yourLocationGoesHere").html(html);
});
});
这是我的 JSON :
{"coord":
{"lon":145.77,"lat":-16.92},
"weather":[{"id":803,"main":"Clouds","description":"broken clouds","icon":"04n"}],
"base":"cmc stations",
"main":{"temp":293.25,"pressure":1019,"humidity":83,"temp_min":289.82,"temp_max":295.37},
"wind":{"speed":5.1,"deg":150},
"clouds":{"all":75},
"rain":{"3h":3},
"dt":1435658272,
"sys":{"type":1,"id":8166,"message":0.0166,"country":"AU","sunrise":1435610796,"sunset":1435650870},
"id":2172797,
"name":"Cairns",
"cod":200}
请帮忙。
答案 0 :(得分:1)
data
正在引用你的json文档,所以它应该是:
html += "<p>'" + data.name + "'</p>";
len
变量只保留长度;)
答案 1 :(得分:1)
您试图获取JSON 长度错误的城市名称。只需:
data.name
这是一个有效的解决方案。希望它有所帮助!
$(document).ready(function(){
$.getJSON("http://api.openweathermap.org/data/2.5/weather? q=London,uk&appid=7f5806c8f3fd28b03e2d6580a50732d6", function (data){
var len = data.length;
var html = "";
html += "<p>'" + data.name + "'</p>";
$(".yourLocationGoesHere").html(html);
});
});