Ajax-запросы
Пример ajax-запроса с передачей заголовка запроса (для отправки файла - из обычного надо удалить) и с чтением ответа, как текста (можно читать как json).
let data = new FormData();
data.append('param1', 'value1');
fetch('', {
method: 'post',
headers: {
"Content-type": "application/x-www-form-urlencoded; charset=UTF-8"
},
body: data
}).then(function(resp) {
if(resp.status == 200){
resp.text().then(function(resp){
console.log(resp);
});
}
});
Пример ajax-запроса с преобразованием кодировки ответа cp1251 => utf8.
fetch('/url/', {
method: 'get'
}).then(function(resp){
if(resp.status == 200){
resp.arrayBuffer().then(function(buffer){
let decoder = new TextDecoder('windows-1251');
let resp = decoder.decode(buffer);
console.log(resp);
});
}
});
Пример синхронного ajax-запроса.
async function exampleFetch() {
const response = await fetch('https://reqres.in/api/users/2');
const json = await response.json();
console.log(json);
}
exampleFetch()