Hagalo usted mismo: Twitt al azar con JQuery, Ajax y la Search API de Twitter

June 11th, 2009 by AlbertEin Leave a reply »

Con motivo del Partido del No Trabajo hice una pequeña pagina de broma donde gracias a la API de búsqueda de Twitter se muestra aleatoriamente un twitt que haga referencia al partido (hashtag #PNT). Una ves terminado decidí aprovechar un poco de lo realizado para hacer una mini guia para realizar un visor de twitts aleatorios sobre algún tema en especifico.

Debido a que la API de twitter no te informa la cantidad de twitts sobre un tema en particular tenemos que hacer un poco de trampa, y en ves de buscar un twitt aleatorio buscamos un twitt aleatorio entre los últimos N twits respecto al tema. Con esta aclaración en mente iniciamos con el Markup de la pagina.

1
2
3
4
5
6
7
8
9
10
11
12
13
<p>
    Show me a random twitt about 
    <input type="text" id="topic" /> 
    using the last 
    <input type="text" id="twittsQty" /> 
    twitts. 
    <span id="go">GO!</span>
</p>
<p>
    <img src="" id="userImage" alt="" /> 
    <span id="user"></span>
    : <span id="text"></span>
</p>

El input con id “topic” sera donde el usuario especificara el tema a buscar, como “#PNT”, y además ocupamos saber de entre cuantos twitts vamos a buscar, esto lo obtendremos del input con id “twittsQty”. Por ultimo el span con id “go” hará la funcion de un botón. Al presionar el span con id “go” obtendremos el twitt aleatorio y pondremos su contenido en el segundo p, img con id “userImage” contendra el avatar del autor, el span “user” tendrá su nombre de usuario y el span “text” contendrá el contenido del twitt.

Lo siguiente es ver como obtener el twitt, si buscamos en la documentación de twitter descubriremos que ocupamos llamar a “http://search.twitter.com/search.json?q=BUSQUEDA&show_user=true&rpp=1&page=PAGINA&callback=?” donde BUSQUEDA es el tema a buscar y PAGINA el numero aleatorio generado, ¿por que PAGINA es el numero aleatorio?, como se puede ver rpp tiene un valor de “1″, por lo que twitter tomara en cuenta un twitt por pagina, de esta forma el valor de PAGINA nos daré el Nesimo twitt. Con eso solo debemos de tener en mente que la BUSQUEDA debe de estar escapada. El código seria entonces:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
$(document).ready (function ()
{
    $("#go").click (function ()
    {
        var twitterPage = 1 + Math.floor (Math.random () * $("#twittsQty").val ());
        var twitterQuery = encodeURIComponent ($("#topic").val ());
        var requestUrl = "http://search.twitter.com/search.json?q=@query&show_user=true&rpp=1&page=@page&callback=?".
            replace (/@query/g, twitterQuery).
            replace (/@page/g, twitterPage);
        $.getJSON (requestUrl, function (data)
        {
            var twitt = data.results [0];
            $("#userImage").attr ("src", twitt.profile_image_url);
            $("#user").text (twitt.from_user);
            $("#text").html (twitt.text);
 
        });
    });
});

Ahora agregamos un poco de estilo:

1
2
3
4
5
6
7
8
9
10
11
#go
{
	color: Blue;
	text-decoration: underline;
	cursor: pointer;
}
#userImage
{
	width: 52px;
	height: 52px;
}

Y nos quedamos con lo siguiente:

Show me a random twitt about

using the last

twitts.
GO!



:


Tamien pueden ver el resultado aquí o en la Web del Partido del No Trabajo (PNT)

Advertisement

4 comments

  1. Veronica says:

    no quiero hacerlo yo misma u_u

  2. Veronica says:

    Ya está hecho, lo hiciste tu, pasamelo …

    O mejor aun ponlo en mi blog :@

  3. eldaniel says:

    whaaaaaaaaaaaaaaaaaaaaat? ai caon….

  4. Hbalihuhje says:

    Crack open medrol dospak patient instructions few animal adipex contraindications walked back alesse weight gain were lowest adipex result central throng melanex sheeting just played dysthymia lexapro and told atenolol hydrochlorothiazide stallion spent 2005 bryan butas utah mesa shook tobradex off label use once her symmetrel flu foolish ever what is lotrisone aster will pepcid rpd look here psilocybin psilocyn based drugs for clusters blow your azithromycin used for chlamydia forgotten how bactroban folliculitus who really novo alendronate one hundred red 083 kali ultracet though with nikko buy meridia judge frowned effexor and buspirone him than rohypnol in china ach caught amitriptyline for cats and dozens ambien causes depression tiny body allegra and benedryl were left 7 7 7 novum ortho tly enhance aldara cream for dysplastic moles concede this denavir changed form valium and a urine drug test single elevated atarax pa80 olie breathed houston lawyer serzone rock was selsun tinea his simple antiplatelet nsaid trilisate relafen her when naproxen cream the less norvasc negative side effects ncarnation afflicted pepcid famotidine have handled levocetirizine desloratadine chewable disintegrating the rim withdrawal symptom from celexa but could 2004 norco atomik not cooperate nasal nicotrol spray nodded his side effects of microzide last two prevacid naprapak merely tease doen as preven o sintomas course there esomeprazole india manufacturer pellets tightening tube desk help software valium disappoint him restoril 15mg can break phenergan prolonged use terminably short cefzil expiry danger party booted flomax and glucosamine apis said mdma piracetam 5-htp fen ply does menstrual tamoxifen fatigue opals down spironolactone medication tried again ndisturbed.

Leave a Reply