ForgeTotal.js 5
it

Total.js 5

Chiama un altro indirizzo con AJAX() dal server

Total.js 5 · total5@0.0.19 httprequestsajax Eseguita con Total.js 5

AJAX('METHOD url', [data], [callback]) fa una richiesta HTTP e ti dà la risposta interpretata. È la forma breve di REQUEST() per le API che parlano JSON: la stessa chiamata che jComponent ha nel browser, così il codice della pagina e quello del server si somigliano.

  • L'indirizzo inizia con un metodo facoltativo: AJAX('POST [https://example.com/api/'](https://example.com/api/'), data). Senza metodo è un GET.
  • data, quando è dato, viene inviato come corpo JSON. La richiesta porta l'intestazione x-requested-with: XMLHttpRequest, quindi dall'altra parte $.xhr è true.
  • La risposta viene interpretata in base al suo tipo di contenuto: il JSON diventa un oggetto, application/x-www-form-urlencoded diventa un oggetto e qualsiasi altra cosa arriva come testo.
  • Quando lo stato è 400 o superiore, la promise viene rifiutata (o il callback riceve prima l'errore) con il corpo interpretato della risposta come errore. Un callback viene chiamato come callback(err, value, response).
  • Senza callback restituisce una promise.

Per le risposte XML usa REQUEST() e analizza tu il corpo: AJAX() è pensato per risposte JSON e di testo.

L'esempio chiama route della stessa applicazione, il cui indirizzo è dato da $.hostname('/'), così non ha bisogno di nessun altro server.

controllers/calls.js
exports.install = function() {
	ROUTE('GET /api/hello/', hello);
	ROUTE('POST /api/echo/', echo);
	ROUTE('GET /api/text/', text);
	ROUTE('GET /api/xml/', xml);
	ROUTE('GET /api/fail/', fail);
	ROUTE('GET /calls/', calls);
};

function hello($) {
	$.json({ hello: 'world', xhr: $.xhr });
}

function echo($) {
	$.json({ received: $.body, xhr: $.xhr });
}

function text($) {
	$.plain('plain text');
}

function xml($) {
	$.xml('<a><b>1</b></a>');
}

function fail($) {
	$.invalid('It is wrong');
}

async function calls($) {

	const base = $.hostname('/');
	const out = {};

	out.hello = await AJAX('GET ' + base + 'api/hello/');
	out.nomethod = await AJAX(base + 'api/hello/');
	out.echo = await AJAX('POST ' + base + 'api/echo/', { a: 1 });
	out.text = await AJAX(base + 'api/text/');

	try {
		await AJAX(base + 'api/fail/');
	} catch (err) {
		out.error = err.message || err;
	}

	out.callback = await new Promise(resolve => AJAX(base + 'api/hello/', (err, value, response) => resolve({ err: err, hello: value.hello, status: response.status })));

	out.xml = await Promise.race([
		AJAX(base + 'api/xml/').then(() => 'answered', () => 'rejected'),
		new Promise(resolve => setTimeout(() => resolve('never answered'), 1000))
	]);

	$.json(out);
}