缓存JSON响应

3
我将使用一些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插件,但对我没有起作用。


尝试使用$.ajax,它具有您正在寻找的功能。 - Manish Parmar
@Mac $.getJSON 是一个针对返回 JSON 数据的服务的 ajax 请求。它是一种快捷方法,因此您不必指定 type: 'JSON',所以他正在使用 ajax ;) - ddavison
2个回答

10
你可以这样使用localStorage:

您可以像这样使用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));
});

因此,在您的特定情况下,您应该在您的 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>");

@kasperTaeymans 是不是指“不必要的”而不是“无需的”?但是,localstorage只能存储字符串,而不能存储javascript对象,那么如果不使用“字符串化”的js对象,你将如何处理呢? - A. Wolff
你可以通过这种方式最多为每个域名节省5MB的空间。http://diveintohtml5.info/storage.html - vumaasha

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参数。

这个也可以工作,但我更喜欢localStorage解决方案。谢谢。 - Dmitry

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接