Di seguito vorrei presentarvi una semplice libreria/wrapper AJAX che ho realizzato per il mondo mobile al fine di essere indipendente sotto questo aspetto da jQuery e per future integrazioni con Node.js.
La libreria è chiamata Ajax
ed ha i seguenti metodi:
get(options)
: esegue una richiesta GETpost(options)
: esegue una richiesta POSTgetJSON(options, callback)
: esegue una richiesta GET con il formato JSON
L'oggetto options
contiene:
url
: l'URL dello script che elaborerà la richiestadata
: i dati passati con la richiesta (sia come query string che come oggetto letterale)complete()
: callback da eseguire quando la richiesta è completa
La libreria ha un oggetto Utils
che possiede dei metodi che possono essere utilizzati anche all'esterno della libreria stessa:
toQueryString()
: trasforma un oggetto in una query stringserialize()
: serializza un formgetQueryString()
: estrae la query string dai link
Esempio d'uso:
var btn = document.getElementById('get');
btn.addEventListener('click', function() {
var output = document.getElementById('output');
Ajax.post({
url: '/echo/html/',
data: {
html: '<p>Test</p>'
},
complete: function(html) {
output.innerHTML = html;
}
});
}, false);