jQuery: ottenere il numero di retweet di un URL senza usare PHP

jQuery: ottenere il numero di retweet di un URL senza usare PHP

Twitter permette di usare anche JSONP per reperire il numero di retweet per un dato URL. Con jQuery la soluzione è semplice.

Per usare JSONP è sufficiente aggiungere &callback=? all'URL delle API di Twitter:


(function( $ ) {
	$.fn.retweets = function( options ) {
		
		options = $.extend({
			url: ""
		}, options);
		
		var twitterURL = "http://urls.api.twitter.com/1/urls/count.json?url=";
		
		return this.each(function() {
			var $element = $( this );
			if( options.url !== "" ) {
				
				var jsonURL = twitterURL + options.url + "&callback=?";
				
				$.getJSON( jsonURL, function( data ) {
					if( data.count ) {
						$element.text( data.count );
					}
				});
			}
			
		});
	};
	
})( jQuery );

Esempio d'uso:


$( ".post" ).each(function() {
	var $post = $( this );
	var permalink = $post.find( ".post-title a" ).attr( "href" );
	var $twitterCount = $post.find( ".retweets" );
	
	$twitterCount.retweets( { url: permalink } );
	
});

Torna su