Call another address with AJAX() from the server
AJAX('METHOD url', [data], [callback]) makes an HTTP request and gives you the parsed answer. It is the short form of REQUEST() for APIs that talk JSON: the same call that jComponent has in the browser, so the code of the page and of the server look alike.
- The address starts with an optional method:
AJAX('POST [https://example.com/api/'](https://example.com/api/'), data). Without a method it is aGET. data, when given, is sent as a JSON body. The request carries the headerx-requested-with: XMLHttpRequest, so on the other side$.xhristrue.- The answer is parsed by its content type: JSON becomes an object,
application/x-www-form-urlencodedbecomes an object, anything else arrives as text. - When the status is 400 or more, the promise is rejected (or the callback gets the error first) with the parsed body of the answer as the error. A callback is called as
callback(err, value, response). - Without a callback it returns a promise.
For XML answers use REQUEST() and parse the body yourself: AJAX() is made for JSON and text answers.
The example calls routes of the same application, whose address $.hostname('/') gives, so that it needs no other server.
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);
}