Notes
Fetch API
// Складываем два числа удаленно let resultA, resultB, resultC; // ES6 подтягивает API, который возвращает промис. function addAsync(num1, num2) { return fetch('http://mysite?num1='+num1+'&num2='+num2) .then(x => x.json() ); } addAsync(1, 2) .then(success => { resultA = success; return resultA; }) .then(success => addAsync(success, 3)) .then(success => { resultB = success; return resultB; }) .then(success => addAsync(success, 4)) .then(success => { resultC = success; return resultC; }) .then(success => { console.log('total: ' + success) console.log(resultA, resultB, resultC) });
index.php :
echo json_encode([$_REQUEST['num1']+$_REQUEST['num2']]); die();
Вариант для POST:
// Складываем два числа удаленно let resultA, resultB, resultC; function addAsync(num1, num2) { const payload = { num1: num1, num2: num2 } return fetch('http://test', { method: "POST", body: new URLSearchParams(payload), headers: new Headers({ 'Content-type': 'application/x-www-form-urlencoded; charset=UTF-8' }) }) .then(x => x.json() ); } addAsync(1, 2) .then(success => { resultA = success; return resultA; }) .then(success => addAsync(success, 3)) .then(success => { resultB = success; return resultB; }) .then(success => addAsync(success, 4)) .then(success => { resultC = success; return resultC; }) .then(success => { console.log('total: ' + success) console.log(resultA, resultB, resultC) });
Версия Fetch API Для отправки JSON на сервер:
let Likes = class Likes {
static toggle(element, event) {
event.preventDefault();
let post_id = element.dataset.post_id
let response = request('/postlike/' + post_id, 'POST', {})
response
.then(data => {
if (data.status === 'ok') {
console.log(data)
} else if (data.status === 'error') {
console.log(data)
} else {
console.log(data)
}
})
}
};
//<meta name="_token" content="{{ csrf_token() }}">
function request(url, method, payload) {
return fetch(url, {
method: method,
body: JSON.stringify(payload),
headers: new Headers({
'Accept': 'application/json',
'Content-type': 'application/json',
'X-CSRF-Token': document.querySelector("meta[name='_token']").getAttribute('content')
})
})
.then(r => r.json())
.catch(error => console.error(error))
}
Афоризм дня:
Кто кажется страшным, тот не может быть свободным от страха. (623)
Leave a reply