Fetch – это JavaScript метод, который используется для отправки запросов на сервер и получения данных. Этот метод является более современной и удобной заменой устаревшего XMLHttpRequest.
В данном примере отправляется GET-запрос на ajax.php, который выводит строку:
<?php
echo 'Строка из ajax.php';
После отправки запроса, его результат обрабатывается в первом then(). Если ответ успешный, то он преобразуется в строку, далее работа с ней идет во втором then().
fetch('https:://example.com/ajax.php')
.then(response => {
return response.text();
})
.then(data => {
console.log(data);
});
Результат в консоли:
Строка из ajax.php
Обработка ошибок
В первом then() можно проверить статус HTTP-запроса и определить, выполнился ли он успешно. В случае возникновения ошибок запроса, они будут обработаны в блоке catch().
JS:
fetch('https:://example.com/script404')
.then(response => {
if (!response.ok) {
throw new Error('Ошибка запроса');
}
return response.text();
})
.then(data => {
console.log(data);
})
.catch(error => {
console.log(error);
});
Результат:
GET https:://example.com/script404 404 (Not Found)
Error: Ошибка запроса
Ответ в JSON
Если от сервера ожидается ответ в формате JSON:
ajax.php:
<?php
$array = array(
'key_1' => 'value_1',
'key_2' => 'value_2'
);
header('Content-Type: application/json');
echo json_encode($array, JSON_UNESCAPED_UNICODE);
JS:
fetch('https:://example.com/ajax.php')
.then(response => {
return response.json();
})
.then(data => {
console.dir(data);
});
Результат:
{
key_1: 'value_1',
key_2: 'value_2'
}
Отправка заголовков на сервер
Можно передавать HTTP-заголовки вторым параметром метода fetch(). Заголовки передаются в формате «ключ: значение».
fetch('https:://example.com/ajax.php', {
headers: {
'Accept': 'application/json',
'Authorization': 'Basic 123456'
}})
.then(response => {
return response.json();
})
.then(data => {
console.dir(data);
});
GET-запрос с параметрами
В GET-запросах параметры передаются непосредственно в URL (?ключ=значение&...). Чтобы сформировать такой URL из объекта параметров можно применить встроенный класс «URL».
JS:
let params = {name: 'Иван', family: 'Иванов'};
let url = new URL('https:://example.com/ajax.php');
url.search = new URLSearchParams(params);
fetch(url, {
headers: {
'Accept': 'application/json'
}})
.then(response => {
return response.json();
})
.then(data => {
console.dir(data);
});
ajax.php
<?php
print_r($_GET);
Результат в переменной $_GET:
Array(
[name] => Иван
[family] => Иванов
)
Для POST-запроса нужно указать method: 'POST' и передать параметры в body в виде «ключ=значение&..» или воспользоваться классом URLSearchParams:
JS:
let data = {
key_1: 'value_1',
key_2: 'value_2'
};
fetch('https:://example.com/ajax.php', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
body: new URLSearchParams(data).toString()
})
.then(response => {
return response.text();
})
.then(data => {
console.log(data);
});
ajax.php
<?php
print_r($_POST);
Результат:
Array(
[key_1] => value_1
[key_2] => value_2
)
Второй пример отправляет данные на сервер в виде JSON.
JS:
let data = {
key_1: 'value_1',
key_2: 'value_2'
};
fetch('https:://example.com/ajax.php', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
})
.then(response => {
return response.text();
})
.then(data => {
console.dir(data);
});
ajax.php
<?php
$data = json_decode(file_get_contents('php://input'), true);
print_r($data);
Результат:
Array(
[key_1] => value_1
[key_2] => value_2
)
<input type="text" id="input_text">
<input type="file" id="input_file">
<input type="submit" value="Отправить" onclick="sendForm();">
<script>
function sendForm(){
var text = document.getElementById('input_text');
var file = document.getElementById('input_file');
var formData = new FormData();
formData.append('text', text.value)
formData.append('file', file.files[0]);
fetch('https:://example.com/ajax.php', {
method: 'POST',
body: formData
})
.then(response => {
return response.text();
})
.then(data => {
console.log(data);
});
}
</script>
ajax.php
<?php
print_r($_POST);
print_r($_FILES);
Результат:
Array(
[text] => Текст из поля
)
Array(
[file] => Array(
[name] => photo.png
[type] => image/png
[tmp_name] => /tmp/????
[error] => 0
[size] => 189415
)
)
Несколько файлов (multiple)
<input type="text" id="input_text">
<input type="file" id="input_file" multiple>
<input type="submit" value="Отправить" onclick="sendForm();">
<script>
function sendForm(){
var text = document.getElementById('input_text');
var file = document.getElementById('input_file');
var formData = new FormData();
formData.append('text', text.value)
for (let item of file.files) {
formData.append('files[]', item);
}
fetch('https:://example.com/ajax.php', {
method: 'POST',
body: formData
})
.then(response => {
return response.text();
})
.then(data => {
console.log(data);
});
}
</script>
Результат:
Array(
[text] => Текст из поля
)
Array(
[files] => Array(
[name] => Array(
[0] => photo.png
[1] => photo-2.png
)
[type] => Array(
[0] => image/png
[1] => image/png
)
[tmp_name] => Array(
[0] => /tmp/????
[1] => /tmp/????
)
[error] => Array(
[0] => 0
[1] => 0
)
[size] => Array(
[0] => 189415
[1] => 88603
)
)
)
Пример использования fetch с методом PUT:
fetch('https:://example.com/update', {
method: 'PUT',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ key: 'value' })
})
.then(response => {
return response.json();
})
.then(data => console.log(data));
Метод DELETE:
fetch('https:://example.com/del/1', {
method: 'DELETE',
})
.then(response => {
return response.json();
})
.then(data => console.log(data));
По умолчанию fetch запросы не отправляет cookies. Чтобы их включить добавить параметр credentials:
fetch('https:://example.com/ajax.php', {
method: 'GET',
credentials: 'include'
})
.then(response => {
return response.text();
})
.then(data => {
console.log(data);
});
async function fetchData() {
try {
const response = await fetch('https:://example.com/ajax.php');
const data = await response.json();
// Далее идет ваш код, который будет выполняться после получения данных
console.log(data);
} catch (error) {
console.error('Error:', error);
}
}
fetchData();





