开发者

Twitter and jQuery , render tweeted links

开发者 https://www.devze.com 2023-02-26 06:29 出处:网络
I am using jquery ajax to pull from the twitter api, i\'m sure there\'s a easy way, but I can\'t find it on how to get the \"tweet\" to render any links that were tweeted to appear as a link. Right no

I am using jquery ajax to pull from the twitter api, i'm sure there's a easy way, but I can't find it on how to get the "tweet" to render any links that were tweeted to appear as a link. Right now it's only text.

$.ajax({  
            type : 'GET',  
            dataType : 'jsonp',  
            url : 'http://search.twitter.com/search.json?q=nettuts&rpp=2',  

            success : function(tweets) {  
               var twitter = $.map(tweets.results, function(obj, index) {  
                  return {  
                     username : obj.from_user,  
                     tweet : obj.text,  
                     imgSource : obj.profile_image_url,  
                     geo : obj.geo  
                  };  
               });  

UPDATE: The following function (plugin) works perfectly.

(function($) {

    $.socialFader = function(options) {

        var settings = {
            tweetHolder : null,
            tweetCount  : 100,
            fadeSpeed   : 500,
           开发者_StackOverflow tweetName: 'jquery'
        };  

        if (options) {
            $.extend(settings, options);
        };

        var URL = "http://search.twitter.com/search.json?q="+settings.tweetName+"&rpp=" + settings.tweetCount + "&callback=?";

        function relative_time(time_value) {

            var values = time_value.split(" ");
            time_value = values[1] + " " + values[2] + ", " + values[5] + " " + values[3];
            var parsed_date = Date.parse(time_value);
            var relative_to = (arguments.length > 1) ? arguments[1] : new Date();
            var delta = parseInt((relative_to.getTime() - parsed_date) / 1000);
            delta = delta + (relative_to.getTimezoneOffset() * 60);
            var r = '';
            if (delta < 60) {
                r = 'a minute ago';
            } else if(delta < 120) {
                r = 'couple of minutes ago';
            } else if(delta < (45*60)) {
                r = (parseInt(delta / 60)).toString() + ' minutes ago';
            } else if(delta < (90*60)) {
                r = 'an hour ago';
            } else if(delta < (24*60*60)) {
                r = '' + (parseInt(delta / 3600)).toString() + ' hours ago';
            } else if(delta < (48*60*60)) {
                r = '1 day ago';
            } else {
                r = (parseInt(delta / 86400)).toString() + ' days ago';
            }

         return r;

        };

        String.prototype.hashify = function() {
            return this.replace(/#([A-Za-z0-9\/\.]*)/g, function(m) {
                return '<a target="_new" href="http://twitter.com/search?q=' + m.replace('#','') + '">' + m + "</a>";
            });
        };

        String.prototype.linkify = function(){
            return this.replace(/[A-Za-z]+:\/\/[A-Za-z0-9-_]+\.[A-Za-z0-9-_:%&\?\/.=]+/, function(m) {
                return m.link(m);
            });
        };

        String.prototype.atify = function() {
            return this.replace(/@[\w]+/g, function(m) {
                return '<a href="http://www.twitter.com/' + m.replace('@','') + '">' + m + "</a>";
            });
        }; 

        $.getJSON(URL, function(JSON) {

            $.each(JSON.results, function(i, tweet) {

                var profilePicture = tweet.profile_image_url;
                var userLink = tweet.from_user;
                var text = tweet.text;
                text = text.linkify().atify().hashify();
                var createdAt = new Date(tweet.created_at);
                var myTweet = '<a href="http://www.twitter.com/' + userLink + '" title="' + userLink + '">' + userLink + '</a> ';
                myTweet += text;
                $(settings.tweetHolder).append('<li class="cycles">' + myTweet + '</li>');

            });

            var elements = $(settings.tweetHolder).children();
            var timeOutStart = 5000;

            function fader(elementId) {
                setTimeout(function() {
                    $(elements[elementId]).fadeOut(settings.fadeSpeed, function() {
                        $(elements[elementId + 1]).fadeIn(settings.fadeSpeed);
                    });
                }, timeOutStart * (elementId));
            };

            for (var j = 0; j < elements.length; j++) {
                           fader(j);
                       };

        });

    };

})(jQuery);

Within my Ready Statement :

$.socialFader({ tweetHolder:"#twitter", tweetName:"nettuts", tweetCount:2 });


Here is a plugin I wrote which really simplifies the tweet/json aggregation then parsing. It fades the tweets in and out. Just grab the needed code. Enjoy.

(function($) {

    $.socialFader = function(options) {

        var settings = {
            tweetHolder : null,
            tweetCount  : 99,
            fadeSpeed   : 500,
        };  

        if (options) {
            $.extend(settings, options);
        };

        var URL = "http://search.twitter.com/search.json?q=jquery&rpp=" + settings.tweetCount + "&callback=?";

        function relative_time(time_value) {

            var values = time_value.split(" ");
            time_value = values[1] + " " + values[2] + ", " + values[5] + " " + values[3];
            var parsed_date = Date.parse(time_value);
            var relative_to = (arguments.length > 1) ? arguments[1] : new Date();
            var delta = parseInt((relative_to.getTime() - parsed_date) / 1000);
            delta = delta + (relative_to.getTimezoneOffset() * 60);
            var r = '';
            if (delta < 60) {
                r = 'a minute ago';
            } else if(delta < 120) {
                r = 'couple of minutes ago';
            } else if(delta < (45*60)) {
                r = (parseInt(delta / 60)).toString() + ' minutes ago';
            } else if(delta < (90*60)) {
                r = 'an hour ago';
            } else if(delta < (24*60*60)) {
                r = '' + (parseInt(delta / 3600)).toString() + ' hours ago';
            } else if(delta < (48*60*60)) {
                r = '1 day ago';
            } else {
                r = (parseInt(delta / 86400)).toString() + ' days ago';
            }

         return r;

        };

        String.prototype.hashify = function() {
            return this.replace(/#([A-Za-z0-9\/\.]*)/g, function(m) {
                return '<a target="_new" href="http://twitter.com/search?q=' + m.replace('#','') + '">' + m + "</a>";
            });
        };

        String.prototype.linkify = function(){
            return this.replace(/[A-Za-z]+:\/\/[A-Za-z0-9-_]+\.[A-Za-z0-9-_:%&\?\/.=]+/, function(m) {
                return m.link(m);
            });
        };

        String.prototype.atify = function() {
            return this.replace(/@[\w]+/g, function(m) {
                return '<a href="http://www.twitter.com/' + m.replace('@','') + '">' + m + "</a>";
            });
        }; 

        $.getJSON(URL, function(JSON) {

            $.each(JSON.results, function(i, tweet) {

                var profilePicture = tweet.profile_image_url;
                var userLink = tweet.from_user;
                var text = tweet.text;
                text = text.linkify().atify().hashify();
                var createdAt = new Date(tweet.created_at);
                var myTweet = '<a href="http://www.twitter.com/' + userLink + '" title="' + userLink + '">' + userLink + '</a> ';
                myTweet += text;
                $(settings.tweetHolder).append('<li class="cycles">' + myTweet + '</li>');

            });

            var elements = $(settings.tweetHolder).children();
            var timeOutStart = 5000;

            function fader(elementId) {
                setTimeout(function() {
                    $(elements[elementId]).fadeOut(settings.fadeSpeed, function() {
                        $(elements[elementId + 1]).fadeIn(settings.fadeSpeed);
                    });
                }, timeOutStart * (elementId));
            };

            for (var j = 0; j < elements.length; j++) {
                fader(j);
            };

        });

    };

})(jQuery);


You need to parse the tweet content, find the urls and then put them in between yourself.


Unfortunately, at the moment, the search API doesn't have the facility to break out tweet entities (i.e., links, mentions, hashtags) like some of the REST API methods. So, you could either parse out the entities yourself (I use regular expressions) or call back into the rest API to get the entities.

If you decide to call back into the REST API, and once you have extracted the status ID from the search API results, you would make a call to statuses/show like the following:

http://api.twitter.com/1/statuses/show/60183527282577408.json?include_entities=true

In the resultant JSON, notice the entities object.

"entities":{"urls":[{"expanded_url":null,"indices":[68,88],"url":"http:\/\/bit.ly\/gWZmaJ"}],"user_mentions":[],"hashtags":[{"text":"wordpress","indices":[89,99]}]}

You can use the above to locate the specific entities in the tweet (which occur between the string positions denoted by the indices property) and transform them appropriately.


If you prefer to parse the entities yourself, here are the (.NET Framework) regular expressions I use:

Link Match Pattern

(?:<\w+.*?>|[^=!:'"/]|^)((?:https?://|www\.)[-\w]+(?:\.[-\w]+)*(?::\d+)?(?:/(?:(?:[~\w\+%-]|(?:[,.;@:][^\s$]))+)?)*(?:\?[\w\+%&=.;:-]+)?(?:\#[\w\-\.]*)?)(?:\p{P}|\s|<|$)

Mention Match Pattern

\B@([\w\d_]+)

Hashtag Match Pattern

(?:(?:^#|[\s\(\[]#(?!\d\s))(\w+(?:[_\-\.\+\/]\w+)*)+)

Twitter also provides an open source library that helps capture Twitter-specific entities like links, mentions and hashtags. This java file contains the code defining the regular expressions that Twitter uses, and this yml file contains test strings and expected outcomes of many unit tests that exercise the regular expressions in the Twitter library.

How you process the tweet is up to you, however I process a copy of the original tweet, and pull all the links first, replacing them in the copy with spaces (so as not to modify the string length.) I capture the start and end locations of the match in the string, along with the matched content. I then pull mentions, then hashtags -- again replacing them in the tweet copy with spaces.

This approach ensures that I don't find false positives for mentions and hashtags in any links in the tweet.


I slightly modified previous one. Nothing lefts after all tweets disappears one by one.

Now it checks if there is any visible tweets and then refreshes tweets.

(function($) {

$.socialFader = function(options) {

    var settings = {
        tweetHolder : null,
        tweetCount  : 99,
        fadeSpeed   : 500,
    };  

    if (options) {
        $.extend(settings, options);
    };

    var URL = "http://search.twitter.com/search.json?q=istanbul&rpp=" + settings.tweetCount + "&callback=?";

    function relative_time(time_value) {

        var values = time_value.split(" ");
        time_value = values[1] + " " + values[2] + ", " + values[5] + " " + values[3];
        var parsed_date = Date.parse(time_value);
        var relative_to = (arguments.length > 1) ? arguments[1] : new Date();
        var delta = parseInt((relative_to.getTime() - parsed_date) / 1000);
        delta = delta + (relative_to.getTimezoneOffset() * 60);
        var r = '';
        if (delta < 60) {
            r = 'a minute ago';
        } else if(delta < 120) {
            r = 'couple of minutes ago';
        } else if(delta < (45*60)) {
            r = (parseInt(delta / 60)).toString() + ' minutes ago';
        } else if(delta < (90*60)) {
            r = 'an hour ago';
        } else if(delta < (24*60*60)) {
            r = '' + (parseInt(delta / 3600)).toString() + ' hours ago';
        } else if(delta < (48*60*60)) {
            r = '1 day ago';
        } else {
            r = (parseInt(delta / 86400)).toString() + ' days ago';
        }

     return r;

    };

    String.prototype.hashify = function() {
        return this.replace(/#([A-Za-z0-9\/\.]*)/g, function(m) {
            return '<a target="_new" href="http://twitter.com/search?q=' + m.replace('#','') + '">' + m + "</a>";
        });
    };

    String.prototype.linkify = function(){
        return this.replace(/[A-Za-z]+:\/\/[A-Za-z0-9-_]+\.[A-Za-z0-9-_:%&\?\/.=]+/, function(m) {
            return m.link(m);
        });
    };

    String.prototype.atify = function() {
        return this.replace(/@[\w]+/g, function(m) {
            return '<a href="http://www.twitter.com/' + m.replace('@','') + '">' + m + "</a>";
        });
    };


    $.getJSON(URL, function(JSON) {

        $(settings.tweetHolder).find('li.cycles').remove();

        $.each(JSON.results, function(i, tweet) {

            var profilePicture = tweet.profile_image_url;
            var userLink = tweet.from_user;
            var text = tweet.text;
            text = text.linkify().atify().hashify();
            var createdAt = new Date(tweet.created_at);
            var myTweet = '<a href="http://www.twitter.com/' + userLink + '" title="' + userLink + '">' + userLink + '</a> ';
            myTweet += text;
            $(settings.tweetHolder).append('<li class="cycles">' + myTweet + '</li>');

        });

        var elements = $(settings.tweetHolder).children();
        var timeOutStart = 5000;

        function fader(elementId) {


            setTimeout(function() {
                $(elements[elementId]).fadeOut(settings.fadeSpeed, function() {
                    $(elements[elementId + 1]).fadeIn(settings.fadeSpeed);
                });
                if (jQuery('#twitter ul li.cycles:visible').length==1) {
                    jQuery.socialFader({ tweetHolder:"#twitter ul", tweetCount:5 });
                }
            }, timeOutStart * (elementId));


        };

        for (var j = 0; j < elements.length; j++) {
            fader(j);
        };

    });

};

})(jQuery);
jQuery(document).ready(function(){
jQuery.socialFader({ tweetHolder:"#twitter ul", tweetCount:5 }); 
});
0

精彩评论

暂无评论...
验证码 换一张
取 消