如何针对地理定位优化jQuery.getJSON()

时间:2016-10-23 23:24:50

标签: javascript jquery getjson

我使用jQuery.getJSON()来获取访问者的位置,并根据该位置显示/隐藏特定的div。因此,由于服务器api限制,我希望在访问期间每个访问者只发送一次请求,可能在客户端使用会话或缓存来存储在访问期间使用的位置;你有什么建议吗?或准备使用的实施?

    <script>
    $(function () {
        $.getJSON('http://freegeoip.net/json/?callback=?', function (location, textStatus, jqXHR) {
            console.log("callback running");
            console.log(textStatus);
            console.log(jqXHR);
            var div = document.getElementById('showadsbayt');
            jQuery('#region-name').html(location.country_code );
              if (location.country_code != 'MA') {
                      div.style.display = 'none';
              }
        });
    });
</script>  

2 个答案:

答案 0 :(得分:0)

使用Web Storage,下面的代码会查找用户是否访问过您的网页,如果没有访问过,ajax会发出请求并设置expire日期,您可以更改天数或设置值0永远是肯定的,如果访问ajax不会请求。

&#13;
&#13;
         < script >
          $(function() {
            var expire = 30; //in days ====> 0 == for ever
            if (!localStorage["visited"] || (+localStorage["visited"] <= new Date().getTime() && +localStorage["visited"] > 0)) {
              localStorage["visited"] = (+expire * 24 * 60 * 60 * 1000) + new Date().getTime();
              localStorage["visited"] = expire == 0 ? 0 : localStorage["visited"];
              $.getJSON('http://freegeoip.net/json/?callback=?', function(location, textStatus, jqXHR) {
                console.log("callback running");
                console.log(textStatus);
                console.log(jqXHR);
                var div = document.getElementById('showadsbayt');
                jQuery('#region-name').html(location.country_code);
                if (location.country_code != 'MA') {
                  div.style.display = 'none';
                }
              });
            }
          }); < /script>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

根据您的实施需要的复杂程度,您的应用程序有多少页以及是否要隐藏用户的位置数据,可以考虑多种选择。我将在下面简要列出它们。

另存为全局变量

这个是非常明显的,我只是为了完整起见而把它放在这里,但如果你正在制作单页应用程序就足够了。

将您感兴趣的位置数据部分作为查询字符串

附加

如果您的应用有多个页面,这可能是最简单的解决方案,您需要做的只是在其中保留数据。这也具有向用户公开位置数据的效果,允许他们例如书签或共享具有给定位置的页面 - 在您的用例中可能需要或可能不需要。

使用cookies

Cookies仅用于此目的 - 将键值对保留在用户的计算机上供以后使用。您只需将位置数据保存为cookie,然后再检查该cookie是否已设置。如果是,请使用cookie中的数据而不是进行API调用。这也会在访问之间持续,因此如果您关心用户可能更改位置的情况,则需要设置较低的到期时间或允许他们重置其位置。

此外,如果你在欧盟,你需要在你的应用程序的某个地方放置愚蠢的cookie法律横幅。

使用localStorage

与cookies相同,除了更灵活和doesn't work on Opera Mini。如果您的位置数据因某些奇怪的原因而巨大,请使用此选项。

显然,这也符合欧盟的cookie法律,所以如果你走这条路,请准备你的横幅。