Cache JSON response

后端 未结 2 1646
长发绾君心
长发绾君心 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 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("");
    });
    else $('#flag').html("");
    

提交回复
热议问题