缓存JSON响应 [英] Cache JSON response
问题描述
我使用一些GeoIP服务在页面上放置国家/地区标志取决于国家IP。我需要缓存我网站上所有页面的JSON响应。
I using some GeoIP service to place country flag on pages depends on country IP. And I need to cache JSON response for all pages on my site.
这段代码放置在 header.php
中:
$.getJSON('http://smart-ip.net/geoip-json?callback=?', function(data) {
$('#flag').html("<a class='fancybox-inline int' href='#international'><img src='/images/flags/"+data.countryCode+".png'></a>");
}
是否可以使用 $来缓存它.ajaxSetup({cache:true})
? - 似乎不起作用。
Is it possible to cache it with $.ajaxSetup({ cache: true })
? - seems to not work.
或者最好使用HTML5 localStorage,但我不知道该怎么做。
Or probably better to use HTML5 localStorage, but I'm not sure how to do that.
我也试过 JSONCache 插件,但它对我不起作用。
I also tried JSONCache plugin, but it did not work for me.
推荐答案
您可以像这样使用localStorage:
You could use localStorage like that:
var smartIp = JSON.parse(localStorage.getItem('smartIp'));
if (!smartIp) $.getJSON('http://smart-ip.net/geoip-json?callback=?', function (data) {
smartIp = localStorage.setItem('smartIp', JSON.stringify(data));
});
因此,在您的具体情况下,您应该在 header.php
页面中使用此代码:
So, in your specific case, you should use this code in your header.php
page:
var smartIp = JSON.parse(localStorage.getItem('smartIp'));
if (!smartIp) $.getJSON('http://smart-ip.net/geoip-json?callback=?', function (data) {
smartIp = localStorage.setItem('smartIp', JSON.stringify(data));
$('#flag').html("<a class='fancybox-inline int' href='#international'><img src='/images/flags/" + data.countryCode + ".png'></a>");
});
else $('#flag').html("<a class='fancybox-inline int' href='#international'><img src='/images/flags/" + smartIp.countryCode + ".png'></a>");
这篇关于缓存JSON响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!