| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455 |
- const fetchHeaders = {
- 'Accept': 'text/html',
- 'Content-Type': 'text/html',
- 'X-Requested-With': 'XMLHttpRequest',
- 'Cache-Control': 'no-cache',
- 'Pragma': 'no-cache',
- 'Expires': '0'
- };
- /**
- * Make an AJAX request.
- *
- * If error, catch return a promise error object:
- *
- * .catch(err => alert(`${err.url}\n\n${err.status} (${err.statusText})`));
- *
- * @param url URL of RESTful api to call
- * @param options the fetch() options
- * @param complete Promise resolve callback
- * @param error Promise reject callback
- * @returns Object {Promise, signal: AbortController}
- */
- export function AjaxReq(url, options, complete, error) {
- let fetchSignal = new AbortController();
- let defaults = {
- headers: fetchHeaders,
- signal: fetchSignal.signal
- };
- // Extend default options
- Object.assign(defaults, options);
- let fetchPromise = fetch(url, defaults)
- .then(resp => {
- if (resp.status === 200)
- return resp.json();
- else
- return Promise.reject(resp);
- })
- .catch(err => {
- if (err.name === 'AbortError')
- return;
- if (err.url !== undefined)
- toastr.error(err.url, `${err.status} (${err.statusText})`);
- else
- toastr.error(err);
- });
- // Add some properties to return value
- return {
- fetchPromise: () => fetchPromise,
- abort: function () {
- fetchSignal.abort()
- }
- };
- }
|