【发布时间】:2014-06-03 18:52:04
【问题描述】:
我最近在我的网站上添加了天气预报。脚本如下:
在页脚之后:
<script type="text/javascript" src="../js/weather.js"></script>
jQuery:
jQuery(document).ready(function($) {
$.ajax({
type: 'GET',
url: "http://api.worldweatheronline.com/free/v1/weather.ashx?q=Gstaad&format=json&num_of_days=5&key=key",
async: false,
contentType: "application/json",
dataType: 'jsonp',
success: function (response) {
var weather = response.data.weather;
var weekdays = ["SUN", "MON", "TUES", "WED", "THU", "FRI", "SAT"];
var ids = ['#first_', '#second_', '#third_', '#fourth_', '#fifth_'];
for (var i = 0; i < weather.length; i++) {
$(ids[i]+"img").attr('src', "http://swissskiresorts.com/wp-content/themes/swiss-ski-resorts/images/day/"+weather[i].weatherCode+".png");
$(ids[i]+"img").attr('title', weather[i].weatherDesc[0].value);
$(ids[i]+"min").text(weather[i].tempMinC);
$(ids[i]+"max").text(weather[i].tempMaxC);
if(i > 0)
{
var d = new Date(weather[i].date);
$(ids[i]+"day").text(weekdays[d.getDay()]);
}
}
console.dir(response);
},
error: function (e) {
console.log(e.message);
}
}); });
我注意到我的网站需要更长的时间才能加载。
有什么可以加快速度的吗?可能会延迟天气预报
【问题讨论】:
-
部分问题在于
async: false。通过这样做,您将锁定屏幕。将 async 设置为 false 只是一个非常非常糟糕的主意。总会有更好的方法。 -
您好,感谢您的提示!我应该将 async 设置为 true 吗?
-
是的,或者只是删除该属性。默认情况下为真。但是,可以肯定的是,我需要查看循环中的内容。
-
亲爱的乔纳森,我已经更新了 sn-p。你相信它可以改进吗?我搞砸了什么吗? :-(
标签: jquery weather-api