简体   繁体   English

将推特推文获取到javascript变量中进行显示…?

[英]Get twitter tweet into javascript variable for display…?

This is going to be a bit more vague than usual as I am looking for direction and don't really have any code to share, yet. 这将比平时更加​​模糊,因为我正在寻找方向并且还没有任何代码可共享。

On my business webpage there is a jquery plugin welcome message (growl style) that is populated by the text I have typed into the JS file. 在我的业务网页上,有一个jquery插件欢迎消息(搜索样式),该消息由我在JS文件中键入的文本填充。 In my hopes to make changing this text easier for my employees I was hoping I could somehow get my most recent tweet into a variable that I could then display automatically... this way there is no changing of code needed. 为了希望让我的员工更轻松地更改文本,我希望可以以某种方式将最新的tweet放入一个变量,然后可以自动显示...这样就无需更改代码。

My hope was to somehow take a string like, "This is a title:this is the message" and be able to separate them into 2 different variable by means of the colon as a seperator. 我希望以某种方式采用一个字符串,例如“ This is a title:this is the message”,并能够使用冒号作为分隔符将它们分成两个不同的变量。 Then I could display these variable using their var name. 然后,我可以使用它们的var名称显示这些变量。

This would be an example of the final product, minus the twitter parsing: 这将是最终产品的示例,减去twitter解析:

jQuery(function($) {
            $("#stdWelcome").ready(function(){
                growlwelcomeid = ("gs"+$.Growl._statsCount);
                $.Growl.show(TwitterMessage, {
                  'title'  : TwitterTitle,
                  'icon'   : "star",
                  'timeout': "10000",
                  'speed': "900"
                });
              });
        }); 

Any help would be greatly appreciated! 任何帮助将不胜感激!

UPDATE: 更新:

So how would something like this look: 那么这样的样子如何:

var Wusername = "username"; 
var Wurl = 'http://api.twitter.com/1/statuses/user_timeline/'+Wusername+'.json?callback=?'; 

$.getJSON(Wurl, function(tweet){ 
    $Wtitle = tweet[0].text.split('|');
}); 

jQuery(function($) {
            $("#stdWelcome").ready(function(){
                growlwelcomeid = ("gs"+$.Growl._statsCount);
                $.Growl.show(Wtitle[1], {
                  'title'  : Wtitle[0],
                  'icon'   : "star",
                  'timeout': "10000",
                  'speed': "900"
                });
              });
        }); 

Thanks again! 再次感谢!

If you had the title and message as seperate tweets you could do the following 如果标题和消息是单独的推文,则可以执行以下操作

var username = "twitter username";
var url = 'http://api.twitter.com/1/statuses/user_timeline/'+username+'.json?callback=?';

$.getJSON(url, function(tweet){
    $title = tweet[0].text;
    $message = tweet[1].text;
});

This probably isn't going to be what you're going for, but here's a twitter widget I coded a while back. 这可能不是您想要的,但这是我不久前编写的一个twitter小部件。 I've included the JS that the client can edit (top section) along with the compressed "gears and working parts" that they shouldn't edit, along with the HTML container. 我包括了客户端可以编辑的JS(顶部)以及压缩的“齿轮和工作部件”,以及它们不应编辑的HTML容器。 Obviously you'll need to add your own CSS and customize as needed. 显然,您需要添加自己的CSS并根据需要自定义。

Here's a working example: ( jsfiddle ) 这是一个工作示例:( jsfiddle

/* Twitter initiates. Enter your username here. */
    jQuery(function($){
          $(".tweeter_widget").tweet({
            join_text: "auto",
            username: "YOUR_USERNAME",
            avatar_size: null,
            count: 1,
            auto_join_text_default: "",
            auto_join_text_ed: "",
            auto_join_text_ing: "",
            auto_join_text_reply: "",
            auto_join_text_url: "",
            loading_text: "loading tweets..."
          })
          // if tweet is over 106 characters long, set the line-height so that the text will wrap to the next line and appear centered in the tweet bar.
          .bind("loaded", function() {
        var $tweet = $(".tweet_first"); // maybe using  $(this)  is better
        var $numWords = $tweet.text().length;
        if (($numWords >= 1) && ($numWords > 106)) {
            $tweet.css({ "line-height": "24px !important" });
        }
        else {
            $tweet.css({ "line-height": "50px !important" });
        }
      });
});

Compressed code to go along with: 压缩后的代码:

//twitter widget
(function(a){a.fn.tweet=function(b){function l(b){var d={};d.item=b;d.source=b.source;d.screen_name=b.from_user||b.user.screen_name;d.avatar_size=c.avatar_size;d.avatar_url=j(b.profile_image_url||b.user.profile_image_url);d.retweet=typeof b.retweeted_status!="undefined";d.tweet_time=g(b.created_at);d.join_text=c.join_text=="auto"?i(b.text):c.join_text;d.tweet_id=b.id_str;d.twitter_base="http://"+c.twitter_url+"/";d.user_url=d.twitter_base+d.screen_name;d.tweet_url=d.user_url+"/status/"+d.tweet_id;d.reply_url=d.twitter_base+"intent/tweet?in_reply_to="+d.tweet_id;d.retweet_url=d.twitter_base+"intent/retweet?tweet_id="+d.tweet_id;d.favorite_url=d.twitter_base+"intent/favorite?tweet_id="+d.tweet_id;d.retweeted_screen_name=d.retweet&&b.retweeted_status.user.screen_name;d.tweet_relative_time=h(d.tweet_time);d.tweet_raw_text=d.retweet?"RT @"+d.retweeted_screen_name+" "+b.retweeted_status.text:b.text;d.tweet_text=a([d.tweet_raw_text]).linkUrl().linkUser().linkHash()[0];d.tweet_text_fancy=a([d.tweet_text]).makeHeart().capAwesome().capEpic()[0];d.user=e('<a class="tweet_user" href="{user_url}" target="_blank">{screen_name}</a>',d);d.join=c.join_text?e(' <span class="tweet_join">{join_text}</span> ',d):" ";d.avatar=d.avatar_size?e('<a class="tweet_avatar" href="{user_url}" target="_blank"><img src="{avatar_url}" height="{avatar_size}" width="{avatar_size}" alt="{screen_name}\'s avatar" title="{screen_name}\'s avatar" border="0"/></a>',d):"";d.time=e('<span class="tweet_time"><a href="{tweet_url}" target="_blank" title="view tweet on twitter">{tweet_relative_time}</a></span>',d);d.text=e('<span class="tweet_text">{tweet_text_fancy}</span>',d);d.reply_action=e('<a class="tweet_action tweet_reply" href="{reply_url}" target="_blank">reply</a>',d);d.retweet_action=e('<a class="tweet_action tweet_retweet" href="{retweet_url}" target="_blank">retweet</a>',d);d.favorite_action=e('<a class="tweet_action tweet_favorite" href="{favorite_url}" target="_blank">favorite</a>',d);return d}function k(){var a="https:"==document.location.protocol?"https:":"http:";var b=c.fetch===null?c.count:c.fetch;if(c.list){return a+"//"+c.twitter_api_url+"/1/"+c.username[0]+"/lists/"+c.list+"/statuses.json?page="+c.page+"&per_page="+b+"&callback=?"}else if(c.favorites){return a+"//"+c.twitter_api_url+"/favorites/"+c.username[0]+".json?page="+c.page+"&count="+b+"&callback=?"}else if(c.query===null&&c.username.length==1){return a+"//"+c.twitter_api_url+"/1/statuses/user_timeline.json?screen_name="+c.username[0]+"&count="+b+(c.retweets?"&include_rts=1":"")+"&page="+c.page+"&callback=?"}else{var d=c.query||"from:"+c.username.join(" OR from:");return a+"//"+c.twitter_search_url+"/search.json?&q="+encodeURIComponent(d)+"&rpp="+b+"&page="+c.page+"&callback=?"}}function j(a){return"https:"==document.location.protocol?a.replace(/^http:/,"https:"):a}function i(a){if(a.match(/^(@([A-Za-z0-9-_]+)) .*/i)){return c.auto_join_text_reply}else if(a.match(d)){return c.auto_join_text_url}else if(a.match(/^((\w+ed)|just) .*/im)){return c.auto_join_text_ed}else if(a.match(/^(\w*ing) .*/i)){return c.auto_join_text_ing}else{return c.auto_join_text_default}}function h(a){var b=arguments.length>1?arguments[1]:new Date;var c=parseInt((b.getTime()-a)/1e3,10);var d="";if(c<60){d=c+" seconds ago"}else if(c<120){d="a minute ago"}else if(c<45*60){d=parseInt(c/60,10).toString()+" minutes ago"}else if(c<2*60*60){d="an hour ago"}else if(c<24*60*60){d=""+parseInt(c/3600,10).toString()+" hours ago"}else if(c<48*60*60){d="a day ago"}else{d=parseInt(c/86400,10).toString()+" days ago"}return" "+d}function g(a){return Date.parse(a.replace(/^([a-z]{3})( [a-z]{3} \d\d?)(.*)( \d{4})$/i,"$1,$2$4$3"))}function f(b,c){return function(){var d=[];this.each(function(){d.push(this.replace(b,c))});return a(d)}}function e(a,b){if(typeof a==="string"){var c=a;for(var d in b){var e=b[d];c=c.replace(new RegExp("{"+d+"}","g"),e===null?"":e)}return c}else return a(b)}var c=a.extend({username:null,list:null,favorites:false,query:null,avatar_size:null,count:3,fetch:null,page:1,retweets:true,intro_text:null,outro_text:null,join_text:null,auto_join_text_default:"i said,",auto_join_text_ed:"i",auto_join_text_ing:"i am",auto_join_text_reply:"i replied to",auto_join_text_url:"i was looking at",loading_text:null,refresh_interval:null,twitter_url:"twitter.com",twitter_api_url:"api.twitter.com",twitter_search_url:"search.twitter.com",template:"{avatar}{time}{join}{text}",comparator:function(a,b){return b["tweet_time"]-a["tweet_time"]},filter:function(a){return true}},b);var d=/\b((?:[a-z][\w-]+:(?:\/{1,3}|[a-z0-9%])|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}\/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'".,<>?«»“”‘’]))/gi;a.extend({tweet:{t:e}});a.fn.extend({linkUrl:f(d,function(a){var b=/^[a-z]+:/i.test(a)?a:"http://"+a;return'<a href="'+b+'" target="_blank">'+a+"</a>"}),linkUser:f(/@(\w+)/gi,'@<a href="http://'+c.twitter_url+'/$1" target="_blank">$1</a>'),linkHash:f(/(?:^| )[\#]+([\w\u00c0-\u00d6\u00d8-\u00f6\u00f8-\u00ff\u0600-\u06ff]+)/gi,' <a href="http://'+c.twitter_search_url+"/search?q=&tag=$1&lang=all"+(c.username&&c.username.length==1?"&from="+c.username.join("%2BOR%2B"):"")+'" target="_blank">#$1</a>'),capAwesome:f(/\b(awesome)\b/gi,'<span class="awesome">$1</span>'),capEpic:f(/\b(epic)\b/gi,'<span class="epic">$1</span>'),makeHeart:f(/(<)+[3]/gi,"<tt class='heart'>&#x2665;</tt>")});return this.each(function(b,d){var f=a('<ul class="tweet_list">').appendTo(d);var g='<p class="tweet_intro">'+c.intro_text+"</p>";var h='<p class="tweet_outro">'+c.outro_text+"</p>";var i=a('<p class="loading">'+c.loading_text+"</p>");if(c.username&&typeof c.username=="string"){c.username=[c.username]}if(c.loading_text)a(d).append(i);a(d).bind("tweet:load",function(){a.getJSON(k(),function(b){if(c.loading_text)i.remove();if(c.intro_text)f.before(g);f.empty();var j=a.map(b.results||b,l);j=a.grep(j,c.filter).sort(c.comparator).slice(0,c.count);f.append(a.map(j,function(a){return"<li>"+e(c.template,a)+"</li>"}).join("")).children("li:first").addClass("tweet_first").end().children("li:odd").addClass("tweet_even").end().children("li:even").addClass("tweet_odd");if(c.outro_text)f.after(h);a(d).trigger("loaded").trigger(j.length===0?"empty":"full");if(c.refresh_interval){window.setTimeout(function(){a(d).trigger("tweet:load")},1e3*c.refresh_interval)}})}).trigger("tweet:load")})}})(jQuery);

and then HTML container: 然后是HTML容器:

<section class="footer-top">
            <div class="f-top-inner"  id="follow-me"> <a class="twit-logo" href="https://twitter.com/intent/follow?original_referer=https%3A%2F%2Ftwitter.com%2Fabout%2Fresources%2Fbuttons&screen_name=YOUR_USER_NAME&source=followbutton&variant=2.0" title="Follow Us" target="_blank" onClick="_gaq.push(['_trackEvent', 'Social', 'Social_Click', 'Twitter']);"></a> 
                <!--tweet position-->
                <div class="tweeter_widget" id="tweetDiv"></div>
            </div>
        </section>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM