我正在使用这样的代码来获取当前的Facebook:
$(document).ready(function() {
$.getJSON('https://graph.facebook.com/<username>?callback=?', function(data) {
var fb_count = data['likes'].toString();
$('#fb_count').html(fb_count);
});
});
但是,当用户浏览页面时,请求再次发送。有没有办法在每个会话中只获取一次数据,并在没有新请求的情况下将获取的值保留在HTML元素中,直到用户关闭浏览器?
感谢您的帮助!
答案 0 :(得分:2)
是的,您可以使用HTML5 localstorage
,
Below code
可以帮到你,
$(document).ready(function() {
if(typeof(Storage)!=="undefined" && localStorage.fb_count)
{
$('#fb_count').html(localStorage.fb_count);
}
else{
$.getJSON('https://graph.facebook.com/<username>?callback=?', function(data) {
var fb_count = data['likes'].toString();
$('#fb_count').html(fb_count);
if(typeof(Storage)!=="undefined")
localStorage.fb_count=fb_count;
});
}
});
答案 1 :(得分:1)
您可以将计数存储在cookie中,并在请求之前检查cookie是否存在 (How do I set/unset cookie with jQuery?)
if( $.cookie("likeCount") === null ){
$.getJSON('https://graph.facebook.com/<username>?callback=?', function(data) {
var fb_count = data['likes'].toString();
$.cookie("likeCount", fb_count);
$('#fb_count').html(fb_count);
});
}
else
$('#fb_count').html($.cookie("likeCount"));
[注意:未经过测试的代码]
答案 2 :(得分:0)
var _facebooker = new function() {
var url = 'https://graph.facebook.com/<username>?callback=?',
threshold = 3,
sKey = "_facebooker",
mode = (window.localStorage ? "storage" : "jcookie");
function getData(){
var data = {};
if (mode === "jcookie")
data = JSON.pase($.cookie(sKey));
else
data = JSON.parse(localStorage.getItem(sKey));
if (typeof data.expired\s == "undefined" || data.expires <= new Date())
return getNewData();
else
return data;
}
function setData(d){
if (mode === "jcookie")
$.cookie(sKey, JSON.stringify(d));
else
localStorage.setItem(sKey, JSON.stringify(d));
return d;
}
function getNewData(){
var data = {};
$.getJSON(url, function(d){
data = {
likeCount: d['likes'],
expires: new Date((new Date()).getTime() + threshold * 60000)
};
setData(data);
});
return data;
}
function getLikeCount(){
return getData().likeCount;
}
return {
"getLikeCount" : getLikeCount
}
}
$(document).ready(function() {
$('#fb_count').html(_facebooker.getLikeCount());
}