16.08.2018, 21:57
(
Последний раз редактировалось CoaPsyFactor; 16.08.2018 в 22:42.
Причина: added note
)
Here is js code, you put this in your main js, or inside <script> tags on index (main) file.
Just replace "PUT_YOUR_URL_HERE" with your url
After request is finished successfully your data will be stored in "window.API_DATA"
NOTE: API Must return proper JSON format
NOTE: ES6 is supported on most current generation browsers, you can checkout compatibility table here
Just replace "PUT_YOUR_URL_HERE" with your url
After request is finished successfully your data will be stored in "window.API_DATA"
NOTE: API Must return proper JSON format
NOTE: ES6 is supported on most current generation browsers, you can checkout compatibility table here
PHP код:
'use strict'
const API_ENDPOINT = 'PUT_YOUR_URL_HERE';
(() => {
const STATUS = {
OK: 200
};
const ERROR = {
NONE: 'NONE',
PARSE: 'INVALID_JSON',
STATUS: 'INVALID_STATUS_CODE'
};
const loadData = (url, data = {}) => {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
// Using traditional function definition
// to prevent invalid context (this)
xhr.onreadystatechange = function () {
if (XMLHttpRequest.DONE !== this.readyState) {
// Not resolving nor rejecting as we need this promise to be done when request is
return;
}
if (STATUS.OK !== this.status) {
// In case that status code is not 200 (OK) we assume something went wrong
return reject({ error: ERROR.STATUS, url });
}
let data;
try {
data = JSON.parse(this.responseText);
} catch (error) {
// In case that server response was not valid json
// we reject this promise with proper error
return reject({ error: ERROR.PARSE, response: this.responseText, url });
}
return resolve({ error: ERROR.NONE, data });
};
xhr.open('GET', url, true);
xhr.send();
});
};
window.onload = () => {
loadData(API_ENDPOINT)
.then((data) => { window.API_DATA = data; })
.catch((error) => { console.error(error); });
};
})();