Cache JSON response

后端 未结 2 1639
长发绾君心
长发绾君心 2020-12-16 08:22

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.

This code placed into

相关标签:
2条回答
  • 2020-12-16 08:38

    $.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.

    0 讨论(0)
  • 2020-12-16 09:02

    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>");
    
    0 讨论(0)
提交回复
热议问题