Il web storage è sicuramente una caratteristica delle API derivate da HTML5 che trova la sua più naturale applicazione nelle web app. Infatti i browser mobile più diffusi (Safari e Webkit Mobile) supportano pienamente questa caratteristica. Possiamo utilizzare il web storage con jQuery per salvare i dati degli utenti nella sessione corrente.
Come prima cosa creiamo un oggetto che funga da wrapper per il web storage:
var Storage = new function() {
this.type = sessionStorage;
this.set = function(item, value) {
this.type.setItem(item, value);
};
this.get = function(item) {
var value = this.type.getItem(item);
return value;
};
this.length = function() {
var len = this.type.length;
return len;
};
this.remove = function(item) {
this.type.removeItem(item);
};
this.clear = function() {
this.type.clear();
};
this.saveAsObject = function(item, obj) {
if (typeof obj === 'object') {
this.set(item, JSON.stringify(obj));
} else {
this.set(item, 'Could not convert to JSON string');
}
};
this.getAsObject = function(item) {
var json = this.get(item);
var obj = JSON.parse(json);
return obj;
};
this.saveSessionData = function(obj) {
for(var prop in obj) {
this.set(prop, obj[prop]);
}
};
}();
Ora ipotizziamo di avere un form di login. Lo script lato server dovrebbe restituire un output in formato JSON con i dati significativi dell'utente corrente. Ad esempio:
{
"firstname": "Gabriele",
"lastname": "Romanato",
"city": "Vasto",
"region": "Abruzzo"
}
Con jQuery inviamo il form in AJAX ed utilizziamo il metodo Storage.saveSessionData()
sull'oggetto JSON restituito:
$('#login-form').submit(function(e) {
e.preventDefault();
$.ajax({
url: 'script.php',
type: 'POST',
dataType: 'json',
data: $(this).serialize(),
success: function(response) {
Storage.saveSessionData(response);
}
});
});
In questo modo non sarà mai necessario ricaricare la pagina per salvare i dati della sessione corrente, i quali risiederanno nella sandbox del browser fino a quando l'utente non lo chiuderà.