Twitter和Facebook要求身份驗(yàn)證來獲取文章的數(shù)量,但事實(shí)證明你可以通過JSONP來獲取這些信息,本文介紹如何使用一些簡單的代碼來獲取并跳過驗(yàn)證這一步,請(qǐng)參考下面的步驟。
我將使用基本的JavaScript來告訴你如何做到這一點(diǎn):
// 獲取文章數(shù)量的封裝對(duì)象
var socialGetter = (function() {
/* JSONP: 獲取腳本的工具函數(shù) */
function injectScript(url) {
var script = document.createElement('script');
script.async = true;
script.src = url;
document.body.appendChild(script);
}
return {
getFacebookCount: function(url, callbackName) {
injectScript('https://graph.facebook.com/?id=' + url + '&callback=' + callbackName);
},
getTwitterCount: function(url, callbackName) {
injectScript('http://urls.api.twitter.com/1/urls/count.json?url=' + url + '&callback=' + callbackName);
}
};
})();
// 回調(diào)方法
function twitterCallback(result) {
result.count && console.log('The count is: ', result.count);
}
function facebookCallback(result) {
result.shares && console.log('The count is: ', result.shares);
}
// 調(diào)用
socialGetter.getFacebookCount('http://davidwalsh.name/twitter-facebook-jsonp', 'facebookCallback');
socialGetter.getTwitterCount('http://davidwalsh.name/twitter-facebook-jsonp', 'twitterCallback');
因?yàn)橛斜姸噍p量級(jí)的 micro-frameworks來處理JSONP,所以本文最重要的部分可能是獲取信息的url了。根據(jù)需要和習(xí)慣選擇你的JSONP工具!
Twitter和Facebook對(duì)于這些請(qǐng)求肯定有數(shù)量和頻率上的限制,所以如果你的網(wǎng)站訪問量很大,則JSONP很可能會(huì)被攔截或屏蔽。一種快速的解決方案是將文章數(shù)量信息存儲(chǔ)在sessionStorage中,但這只是針對(duì)單個(gè)用戶的方式。如果你運(yùn)行的網(wǎng)站流量較大,你最好選擇在服務(wù)器端抓取數(shù)據(jù)并緩存下來,并在一定的時(shí)間內(nèi)自動(dòng)刷新。
GET URL:
http://cdn.api.twitter.com/1/urls/count.JSon?url=http://stylehatch.co
返回結(jié)果:
{
"count":528,
"url":"http://stylehatch.co/"
}
GET URL:
http://graph.facebook.com/?id=http://stylehatch.co
返回結(jié)果:
{
"id": "http://stylehatch.co",
"shares": 61
}
GET URL:
http://api.pinterest.com/v1/urls/count.json?callback=&url=http://stylehatch.co
返回結(jié)果:
({"count": 0, "url": "http://stylehatch.co"})
GET URL:
http://www.linkedin.com/countserv/count/share?url=http://stylehatch.co&format=json
返回結(jié)果:
{
"count":17,
"fCnt":"17",
"fCntPlusOne":"18",
"url":"http:\/\/stylehatch.co"
}
POST URL:
https://clients6.google.com/rpc?key=YOUR_API_KEY
POST body:
[{
"method":"pos.plusones.get",
"id":"p",
"params":{
"nolog":true,
"id":"http://stylehatch.co/",
"source":"widget",
"userId":"@viewer",
"groupId":"@self"
},
"jsonrpc":"2.0",
"key":"p",
"apiVersion":"v1"
}]
返回結(jié)果:
[{
"result": {
"kind": "pos#plusones",
"id": "http://stylehatch.co/",
"isSetByViewer": false,
"metadata": {
"type": "URL",
"globalCounts": {
"count": 3097.0
}
}
} ,
"id": "p"
}]
GET URL:
http://www.stumbleupon.com/services/1.01/badge.getinfo?url=http://stylehatch.co
返回結(jié)果:
{
"result":{
"url":"http:\/\/stylehatch.co\/",
"in_index":true,
"publicid":"1iOLcK",
"views":39,
"title":"Style Hatch - Hand Crafted Digital Goods",
"thumbnail":"http:\/\/cdn.stumble-upon.com\/mthumb\/941\/72725941.jpg",
"thumbnail_b":"http:\/\/cdn.stumble-upon.com\/bthumb\/941\/72725941.jpg",
"submit_link":"http:\/\/www.stumbleupon.com\/submit\/?url=http:\/\/stylehatch.co\/",
"badge_link":"http:\/\/www.stumbleupon.com\/badge\/?url=http:\/\/stylehatch.co\/",
"info_link":"http:\/\/www.stumbleupon.com\/url\/stylehatch.co\/"
},
"timestamp":1336520555,
"success":true
}
這里有一個(gè)網(wǎng)站封裝了一個(gè)小插件,專門用來在頁面上顯示社交網(wǎng)站分享工具條,可以直接拿過來用,比較方便!http://sharrre.com/
Facebook,Twitter,LinkedIn比較常用,給出調(diào)用API的例子:
// Facebook
$.getJSON("http://graph.facebook.com/?id=http://stylehatch.co", function (d) {
$("#fackbook_count").text("The Facebook Share count is: " + d.shares);
});
// Twitter
$.getJSON("http://cdn.api.twitter.com/1/urls/count.json?url=http://stylehatch.co&callback=?", function (d) {
$("#twitter_count").text("The Twitter Share count is: " + d.count);
});
// LinkedIn
$.getJSON("http://www.linkedin.com/countserv/count/share?url=http://stylehatch.co&callback=?", function (d) {
$("#linkedin_count").text("The LinkdeIn Share count is: " + d.count);
});
IE瀏覽器可能會(huì)無法正確獲取到Facebook返回的數(shù)據(jù),可以嘗試在URL后面加上&callback=?,這樣JQuery會(huì)將它當(dāng)成JSONP來調(diào)用。
Facebook還有另一個(gè)API返回XML數(shù)據(jù),調(diào)用方法是這樣的:
$.get("http://api.facebook.com/method/links.getStats?urls=http://stylehatch.co", function (d) {
$("#fackbook_count").text("The Facebook Share count is: " + $(d).find("total_count").text());
});
如果在IE瀏覽器下出現(xiàn)No Transport錯(cuò)誤而無法獲取到Facebook返回的數(shù)據(jù),嘗試在JavaScript代碼的最前面加上$.support.cors = true;允許跨域訪問數(shù)據(jù)。
我們將上面Facebook,Twitter,LinkedIn三個(gè)社交網(wǎng)站的API進(jìn)行封裝,以方便頁面調(diào)用。
$.fn.getShareCount = function (url) {
var self = this;
var displayShareCount = function (val, obj) {
if (!isNaN(val) && val > 0) {
obj.show();
if (val > 999) {
obj.attr("title", val);
obj.text("500+");
}
else
obj.text(val);
}
};
return {
facebook: function () {
$.get("http://api.facebook.com/method/links.getStats?urls=" + url, function (d) {
var c = $(d).find("total_count").text();
self.each(function () { displayShareCount(c, $(this)); });
});
},
twitter: function () {
$.getJSON("http://cdn.api.twitter.com/1/urls/count.json?url=" + url + "&callback=?", function (d) {
self.each(function () { displayShareCount(d.count, $(this)); });
});
},
linkedin: function () {
$.getJSON("http://www.linkedin.com/countserv/count/share?url=" + url + "&callback=?", function (d) {
self.each(function () { displayShareCount(d.count, $(this)); });
});
}
};
};
然后在頁面上這樣調(diào)用:
$(function () {
var shareUrl = window.location.href.toLowerCase();
$('#fackbook_count').getShareCount(shareUrl).facebook();
$('#twitter_count').getShareCount(shareUrl).twitter();
$('#linkedin_count').getShareCount(shareUrl).linkedin();
});
更多建議: