Dmi*_*try 3 jquery html5 json geoip
我使用一些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>");
}
Run Code Online (Sandbox Code Playgroud)
是否可以缓存它$.ajaxSetup({ cache: true })? - 似乎行不通.
或者最好使用HTML5 localStorage,但我不知道该怎么做.
我也试过JSONCache插件,但它对我不起作用.
您可以像这样使用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));
});
Run Code Online (Sandbox Code Playgroud)
因此,在您的特定情况下,您应该在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>");
Run Code Online (Sandbox Code Playgroud)
小智 8
$.getJSON() 相当于
$.ajax({
dataType: "json",
url: 'http://smart-ip.net/geoip-json/ip_address',
data: data,
success: function(data){ // do something here }
});
Run Code Online (Sandbox Code Playgroud)
在此表单中,您可以添加其他参数,例如cache:true,或您可能需要的任何其他$ .ajax参数.
| 归档时间: |
|
| 查看次数: |
14840 次 |
| 最近记录: |