La funzionalità web database introdotta originariamente da HTML5 ci permette di creare un database locale gestito dal browser su cui operare tramite normali query SQL. In questo articolo vedremo come gestire i web database con jQuery.
Vogliamo creare un semplice database locale con una sola tabella che conterrà i nostri ultimi 10 tweet. Ciascun tweet avrà tre campi:
id
– L'ID del tweet.text
– Il testo del tweet.created_at
– La data di creazione del tweet.
Una volta creata la tabella e popolata con i nostri tweet vogliamo permettere agli utenti di effettuare ricerche su di esso. Per prima cosa creiamo il database e la tabella:
var TwitterDB = {
fn: {
db: null,
createDB: function () {
if (window.openDatabase) {
// creo il database locale
this.db = openDatabase('jquerytweets', '1.0', 'jQuery Tweets Database', 200000);
}
if (this.db) {
this.db.transaction(function (transaction) {
// elimino la tabella se esiste già
transaction.executeSql('DROP TABLE IF EXISTS tweets', []);
// creo la tabella se non esiste
transaction.executeSql('CREATE TABLE IF NOT EXISTS tweets (id REAL UNIQUE, text TEXT, created_at TEXT)', []);
});
}
},
// continua
}
};
Come si può notare, viene creata prima un'istanza del database specificando il nome, la versione, la descrizione e le dimensioni. Quindi si eseguono le transazioni sul database usando normali query SQL.
Il metodo executeSql()
usa dei segnaposto (?
) per le query che utilizzano variabili. Le variabili infatti vanno inserite nel corretto ordine all'interno dell'array passato come secondo parametro a questo metodo.
Ora possiamo inserire i tweet nella tabella del database:
insertTweets: function () {
var $db = this.db;
var twitterApiURL = 'http://api.twitter.com/1/statuses/user_timeline.json?&screen_name=gabromanato&callback=?&count=10';
$.getJSON(twitterApiURL, function (tweets) {
var items = tweets;
$db.transaction(function (transaction) {
for (var i = 0; i < items.length; i++) {
transaction.executeSql('INSERT INTO tweets (id, text, created_at) VALUES (?, ?, ?)', [items[i].id, items[i].text, items[i].created_at]);
}
});
});
}, // continua
A questo punto dobbiamo abilitare la funzionalità di ricerca. Possiamo selezionare i tweet in ordine discendente (dal più recente in poi) e usare la query dell'utente per effettuare una ricerca testuale all'interno del campo text
:
searchTweets: function () {
var $db = this.db;
$('#query').on('submit', function (e) {
e.preventDefault();
var q = $('#q').val();
$('#tweets').empty();
$db.transaction(function (transaction) {
transaction.executeSql('SELECT * FROM tweets ORDER BY id DESC', [], function (transaction, results) {
if (results.rows && results.rows.length) {
for (var i = 0; i < results.rows.length; i++) {
var result = results.rows.item(i).text;
var re = new RegExp(q, 'i');
if (re.test(result)) {
$('<p/>').text(result).appendTo('#tweets');
}
}
}
});
});
});
}
Incontriamo il parametro results
della funzione di callback del metodo executeSql()
. Questo parametro contiene un array di righe (rows
) al cui interno troveremo i risultati richiesti come proprietà di tali oggetti.
Concludiamo il nostro codice con l'inizializzazione del nostro oggetto principale:
var TwitterDB = {
//...
init: function () {
this.fn.createDB();
this.fn.insertTweets();
this.fn.searchTweets();
}
};
$(function () {
TwitterDB.init();
});