Sui
browser moderni è disponibile la comodissima
FetchAPI tramite il comando
JavaScript fetch:
var url = "/demo";
fetch(url, {
method: "POST",
mode: "cors", // parametro vincolante per le chiamate cross domain
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ value: 1 }),
})
.then((response) => response.json())
.then((data) => {
console.log(data);
})
.catch((error) => {
console.error(error);
});
Permette di gestire le chiamate
AJAX senza l'uso di librerie esterne come
JQuery ovvero solo in
Vanilla JS.
Internet Explorer
Tutto bellissimo tranne per
Internet Explorer.
Infatti questo
browser non supporta la
FetchAPI.
Ovviamente nei nuovi sviluppi ormai non è più necessario supportare
IE in quanto la diffusione è quasi prossima a
zero ma soprattutto
non è da considerarsi
sicuro.
Ci sono comunque casi, ad esempio le
intranet aziendali, in cui
Internet Explorer è ancora molto diffuso.
Se dobbiamo proprio supportare
IE, nel caso di modifiche all'esistente, possiamo iniziare a familiarizzare con la nuova API tramite una funzione
Polyfill come questa:
if (typeof fetch === 'undefined') {
/**
* implementazione PARZIALE di fetch per Internet Explorer
* parametro header.mode: non gestito, il default è 'cors'
* @param {*} url
* @param {*} options es. {method: "POST", mode: "cors", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ value: 1 }) }
* @returns un oggetto con metodi then(...) e catch(...)
*/
var fetch = function (url, options) {
console.log('fetch polyfill by https://www.sgart.it');
var thenFunctions = []; // non gestisce catene di then o catch
var catchFunctions = [];
var returnObject = {
then: function (fn) {
thenFunctions.push(fn);
return returnObject;
},
catch: function (fn) {
catchFunctions.push(fn);
return returnObject;
}
};
var xHttp = new XMLHttpRequest();
xHttp.onreadystatechange = function () {
if (this.readyState === 4) {
this.ok = this.status >= 200 && this.status <= 299;
if (this.status === 200) {
console.log('then');
this.json = function () {
return JSON.parse(this.responseText);
};
var data = this;
for (var i = 0; i < thenFunctions.length; i++) {
var fn = thenFunctions[i];
data = fn(data);
}
} else {
var error = { status: this.status, message: this.responseText };
console.error('catch', error);
for (var i = 0; i < catchFunctions.length; i++) {
var fn = catchFunctions[i];
error = fn(error);
}
}
}
};
var method = options && options.method ? options.method : 'GET';
xHttp.open(method, url, true);
if (options && options.headers) {
for (var key in options.headers) {
var value = options.headers[key];
xHttp.setRequestHeader(key, value);
}
}
if (options && options.body) {
var data = options.body;
xHttp.send(data);
} else {
xHttp.send();
}
return returnObject;
}
}
Attenzione è un supporto
parziale alle
FetchAPI non gestisce le casistiche più complesse, ma funziona anche per le chiamate
CORS.
Da usare solo per
Internet Exploer, per gli altri
browser non serve è supportata nativamente.
In ogni caso, se la funzione
fetch è già presente, il
Polyfill non viene applicato.
Per una alternativa alla
Fetch API in
Vanilla JS vedi
Chiamata Ajax in JavaScript senza framework (XMLHttpRequest).