Ускоренные курсы AJAX и Fetch API

В своей карьере я использовал как AJAX, так и Fetch API (совсем недавно). Если вам когда-либо приходилось получать удаленные данные из API или внутреннего URL-адреса PHP, скорее всего, вы использовали один или другой.

В этом уроке я покажу вам, как использовать оба метода на тот случай, если вы знакомы только с одним или другим. Мы будем использовать PHP для создания объекта JSON, который получает список всех стран (если я что-то пропустил, извините, я скопировал список).

AJAX годами тестировался в jQuery и в какой-то момент стал методом перехода. С возвращением Vanilla JS новые опции, такие как встроенный API-интерфейс Fetch, используются все чаще. В основном это связано с его простотой использования, а поскольку он встроен в JavaScript, вам больше не нужна инфраструктура или библиотека для его использования.

Структура файла

/index.html
/js/init.js
/src/functions.php

Для простоты я буду извлекать данные из локального файла PHP, который возвращает объект JSON, который затем можно использовать с помощью AJAX или Fetch. Вы можете использовать этот файл PHP для обоих методов. В файл init.js вы должны добавить код AJAX или Fetch, указанный ниже.

Настройка HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>How To Use AJAX or Fetch</title>
    <style>
        .country-list { padding:0; margin:0;}
        .country-list li { list-style-type: none; display:block;}
    </style>
</head>
<body>
    <label>Using AJAX (jQuery)</label>
    <br>
    <input type="text" id="ajaxcountry" placeholder="Country Name">
    <br>
    <br>
    <label>Using Fetch (Vanilla JS)</label>
    <br>
    <input type="text" id="vanillacountry" placeholder="Country Name">
    <br>
    <ul class="country-list"></ul>
    <script src="/js/init.js"></script>
</body>
</html>

Если вы используете метод AJAX, вы можете добавить ссылку на jQuery непосредственно над ссылкой на файл /js/init.js. Это будет выглядеть так:

<script src="https://code.jquery.com/jquery-2.1.1.min.js" type="text/javascript"></script>

Настройте наш файл PHP

В файл /src/functions.php вы можете добавить следующие фиктивные данные.

Во-первых, нам нужно добавить массив стран. Вы можете найти такие массивы на GitHub, но мой должен быть довольно обширным. Весь мой файл PHP приведен ниже, чтобы вы могли видеть, куда он идет.

<?php
// list of countries as an array to testing purposes
$countries = ["Afghanistan", "Albania", "Algeria", "American Samoa", "Andorra", "Angola", "Anguilla", "Antarctica", "Antigua and Barbuda", "Argentina", "Armenia", "Aruba", "Australia", "Austria", "Azerbaijan", "Bahamas", "Bahrain", "Bangladesh", "Barbados", "Belarus", "Belgium", "Belize", "Benin", "Bermuda", "Bhutan", "Bolivia", "Bosnia and Herzegowina", "Botswana", "Bouvet Island", "Brazil", "British Indian Ocean Territory", "Brunei Darussalam", "Bulgaria", "Burkina Faso", "Burundi", "Cambodia", "Cameroon", "Canada", "Cape Verde", "Cayman Islands", "Central African Republic", "Chad", "Chile", "China", "Christmas Island", "Cocos (Keeling) Islands", "Colombia", "Comoros", "Congo", "Congo, the Democratic Republic of the", "Cook Islands", "Costa Rica", "Cote d'Ivoire", "Croatia (Hrvatska)", "Cuba", "Cyprus", "Czech Republic", "Denmark", "Djibouti", "Dominica", "Dominican Republic", "East Timor", "Ecuador", "Egypt", "El Salvador", "Equatorial Guinea", "Eritrea", "Estonia", "Ethiopia", "Falkland Islands (Malvinas)", "Faroe Islands", "Fiji", "Finland", "France", "France Metropolitan", "French Guiana", "French Polynesia", "French Southern Territories", "Gabon", "Gambia", "Georgia", "Germany", "Ghana", "Gibraltar", "Greece", "Greenland", "Grenada", "Guadeloupe", "Guam", "Guatemala", "Guinea", "Guinea-Bissau", "Guyana", "Haiti", "Heard and Mc Donald Islands", "Holy See (Vatican City State)", "Honduras", "Hong Kong", "Hungary", "Iceland", "India", "Indonesia", "Iran (Islamic Republic of)", "Iraq", "Ireland", "Israel", "Italy", "Jamaica", "Japan", "Jordan", "Kazakhstan", "Kenya", "Kiribati", "Korea, Democratic People's Republic of", "Korea, Republic of", "Kuwait", "Kyrgyzstan", "Lao, People's Democratic Republic", "Latvia", "Lebanon", "Lesotho", "Liberia", "Libyan Arab Jamahiriya", "Liechtenstein", "Lithuania", "Luxembourg", "Macau", "Macedonia, The Former Yugoslav Republic of", "Madagascar", "Malawi", "Malaysia", "Maldives", "Mali", "Malta", "Marshall Islands", "Martinique", "Mauritania", "Mauritius", "Mayotte", "Mexico", "Micronesia, Federated States of", "Moldova, Republic of", "Monaco", "Mongolia", "Montserrat", "Morocco", "Mozambique", "Myanmar", "Namibia", "Nauru", "Nepal", "Netherlands", "Netherlands Antilles", "New Caledonia", "NewReunion", "Romania", "Russian Federation", "Rwanda", "Saint Kitts and Nevis", "Saint Lucia", "Saint Vincent and the Grenadines", "Sa Zealand", "Nicaragua", "Niger", "Nigeria", "Niue", "Norfolk Island", "Northern Mariana Islands", "Norway", "Oman", "Pakistan", "Palau", "Panama", "Papua New Guinea", "Paraguay", "Peru", "Philippines", "Pitcairn", "Poland", "Portugal", "Puerto Rico", "Qatar", "moa", "San Marino", "Sao Tome and Principe", "Saudi Arabia", "Senegal", "Seychelles", "Sierra Leone", "Singapore", "Slovakia (Slovak Republic)", "Slovenia", "Solomon Islands", "Somalia", "South Africa", "South Georgia and the South Sandwich Islands", "Spain", "Sri Lanka", "St. Helena", "St. Pierre and Miquelon", "Sudan", "Suriname", "Svalbard and Jan Mayen Islands", "Swaziland", "Sweden", "Switzerland", "Syrian Arab Republic", "Taiwan, Province of China", "Tajikistan", "Tanzania, United Republic of", "Thailand", "Togo", "Tokelau", "Tonga", "Trinidad and Tobago", "Tunisia", "Turkey", "Turkmenistan", "Turks and Caicos Islands", "Tuvalu", "Uganda", "Ukraine", "United Arab Emirates", "United Kingdom", "United States", "United States Minor Outlying Islands", "Uruguay", "Uzbekistan", "Vanuatu", "Venezuela", "Vietnam", "Virgin Islands (British)", "Virgin Islands (U.S.)", "Wallis and Futuna Islands", "Western Sahara", "Yemen", "Yugoslavia", "Zambia", "Zimbabwe"];
$name = $_POST['search']; // get the search term that is entered into the search box
$match = []; // create an empty array
if(strlen($name) > 0) { // check if the search term is greater than 0 characters
    for ($i = 0; $i < count($countries); $i++) { // loop through the array
        $formArr = strtolower(substr($countries[$i], 0, strlen($name))); // get the first x characters of the array
        if(strtolower($name) == $formArr) { // check if the search term matches the array
            array_push($match, $countries[$i]); // add the array to the match array
        }
    }
}
echo json_encode($match); // return the array as a json object

Теперь код PHP должен быть установлен для ответа с использованием AJAX или Fetch. Это простой код, и его можно заменить прямым вызовом API, если хотите, но чтобы сделать это руководство более простым, мы просто вызываем файл PHP.

АЯКС-метод

В файле /js/init.js вы можете использовать jQuery для ссылки на метод AJAX.

ПРИМЕЧАНИЕ. Убедитесь, что в файл index.html выше добавлен тег jQuery.

$(document).ready(function () {
    $("#ajaxcountry").on("keyup", function () { // when keyup
        $.ajax({ // ajax call starts
            type: "POST", // POST method
            url: "/src/functions.php", // the file to call
            data: "search=" + $(this).val(), // value of the input
            success: function (response) { // data is returned from the php page
                $(".country-list").html(""); // remove all child nodes of the div
                $(".country-list").show(); // show the div
                $.each(JSON.parse(response), function (i, item) { // loop though the response
                    $(".country-list").append("<li>" + item + "</li>"); // append the response to the div
                });
            },
        });
    });
    $(".country-list").on("click", "li", function () { // when a list item is clicked
        var val = $(this).text(); // get the text of the clicked item
        selectCountry(val) // call the function to select the item
    });
});
function selectCountry(val) { // function to select the item
    $("#ajaxcountry").val(val); // set the value of the input to the value of the clicked item
    $(".country-list").hide(); // hide the div
}

Используя приведенный выше код, мы инициируем вызов AJAX для файла /src/functions.php, затем анализируем результаты JSON перед добавлением их в наш HTML-объект .country-list.

Событие щелчка для элемента .country-list теперь должно принимать динамический список и давать вам возможность установить текстовое поле на основе выбора.

Получить метод API

ПРИМЕЧАНИЕ. В этом методе используются встроенные функции Vanilla JS, поэтому вам не нужно добавлять какие-либо ссылки на jQuery.

window.addEventListener("load", function(e) { // when the page loads
    document.querySelector("#vanillacountry").addEventListener("keyup", function (e) { // when keyup
        fetch("/src/functions.php", { // fetch the file
            method: "POST", // POST method
            headers: { "Content-Type": "application/x-www-form-urlencoded" }, // set the content type
            body: "search=" + this.value // value of the input
        }).then(function (response) { // when the response is returned
            return response.text(); // return the response
        }).then(function (response) { // when the response is returned
            var countryList = document.querySelector(".country-list"); // get the country list
            countryList.innerHTML = ""; // remove all child nodes of the div
            countryList.style.display = "block"; // show the div
            JSON.parse(response).forEach(function (item) { // loop though the response
                var li = document.createElement("li"); // create a list item
                li.innerHTML = item; // set the text of the list item
                countryList.appendChild(li); // append the list item to the div
            });
        });
    });
});
document.querySelector(".country-list").addEventListener("click", function (e) { // when a list item is clicked
    if (e.target.tagName === "LI") { // if the clicked item is a list item
        selectCountry(e.target.innerHTML); // call the function to select the item
    }
});
function selectCountry(val) { // function to select the item
    document.querySelector("#vanillacountry").value = val; // set the value of the input to the value of the clicked item
    countryList.style.display = "none"; // hide the div
}

Итак, если вы сравниваете AJAX с Fetch API, они очень похожи. Код между ними почти зеркально отражает друг друга, но один использует функции jQuery, а другой использует функции JS.

Используя приведенный выше код, мы инициируем вызов Fetch API для файла /src/functions.php, затем анализируем результаты JSON, прежде чем добавить их к нашему HTML-объекту .country-list.

Событие щелчка для элемента .country-list теперь должно принимать динамический список и давать вам возможность установить текстовое поле на основе выбора.

Заключение

Лично мне нравится Fetch API. Я использовал jQuery так долго, что забыл, как использовать Vanilla JS, но как только я смог по-настоящему вернуться к нему, я почувствовал, что он лучше, поскольку он быстрее и занимает гораздо меньше места на моих серверах.

Вы можете использовать любой из них в зависимости от ваших потребностей. Fetch возвращается к Vanilla JS и дает вам гораздо больше гибкости, если вы планируете использовать другие фреймворки помимо jQuery (React, Vue и т. д.).