Cache JSON response

送分小仙女□ 提交于 2019-11-29 02:38:49

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

DEMO

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

$.getJSON() is equivalent to

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

In this form you can add additional parameters, such as cache:true, or any other $.ajax parameters you might need.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!