可以使用localStorage / sessionStorage缓存.getJSON查询,或者在cookie中缓存X小时吗?
<script>
jQuery(document).ready(function($) {
var rateYesterday;
$.getJSON( "http://api.fixer.io/<?php echo date("Y-m-d", time() - 60 * 60 * 24) ?>", function(dd) {
cache: true;
rateYesterday = dd;
});
var rateToday;
$.getJSON( "http://api.fixer.io/latest", function(jd) {
rateToday = jd;
cache: true;
console.log( "success" + rateToday['rates']['HUF'] );
$('#first').html(rateToday['rates']['HUF']);
$('#second').html(rateToday['rates']['CZK']);
if (rateToday['rates']['HUF'] >= rateYesterday['rates']['HUF'] ) {
$('#firstrate').addClass('goood');
}
if (rateToday['rates']['HUF'] < rateYesterday['rates']['HUF'] ) {
$('#firstrate').addClass('baaad');
}
if (rateToday['rates']['CZK'] >= rateYesterday['rates']['CZK'] ) {
$('#secondrate').addClass('goood');
}
if (rateToday['rates']['CZK'] < rateYesterday['rates']['CZK'] ) {
$('#secondrate').addClass('baaad');
}
})
.fail(function() {
console.log( "error" );
})
});
</script>
我在代码中设置了cache:true,但它并没有真正缓存数据。
有趣的是,如果我按几次刷新按钮,我有时会得到:
TypeError: rateYesterday is undefined
if (rateToday['rates']['HUF'] >= rateYesterday['rates']['HUF'] ) {
答案 0 :(得分:1)
正如评论所指出的那样,在服务器上可能会做得更好,但为了解决这个问题并回答问题,你可以这样做。这是一种方式:
function HourCache (jsonData) {
var stringValue;
if (typeof jsonData === 'string') {
stringValue = jsonData;
}
else {
stringValue = JSON.stringify(jsonData)
}
sessionStorage.setItem('jsonData', stringValue);
setTimeout(
function () {
sessionStorage.removeItem('jsonData');
}, 3600000
);
}