缓存JSON响应

时间:2013-06-29 10:38:16

标签: jquery json html5 geoip

我使用一些GeoIP服务在页面上放置国家/地区标志取决于国家/地区IP。我需要为我网站上的所有页面缓存JSON响应。

此代码放入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 })对其进行缓存? - 似乎不起作用。

或者最好使用HTML5 localStorage,但我不知道该怎么做。

我也尝试了JSONCache插件,但它对我不起作用。

2 个答案:

答案 0 :(得分:9)

你可以像这样使用localStorage:

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));
});

DEMO

因此,在您的具体情况下,您应该在header.php页面中使用此代码:

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>");

答案 1 :(得分:8)

$.getJSON()相当于

$.ajax({
  dataType: "json",
  url: 'http://smart-ip.net/geoip-json/ip_address',
  data: data,
  success: function(data){ // do something here }
});

在此表单中,您可以添加其他参数,例如cache:true或您可能需要的任何其他$ .ajax参数。

相关问题