В своей карьере я использовал как AJAX, так и Fetch API (в последнее время). Если вам когда-либо приходилось получать удаленные данные из API или внутреннего PHP URL, скорее всего, вы использовали тот или иной метод.
В этом уроке я покажу вам, как использовать оба метода, на случай, если вы знакомы только с одним или другим. Мы будем использовать PHP для создания объекта JSON, который получает список всех стран (если я пропустил одну, извините, я скопировал список).
AJAX был опробован и испытан в течение многих лет в jQuery и в какой-то момент был основным методом. С возвращением Vanilla JS все чаще используются новые возможности, такие как встроенный Fetch API. В основном это связано с простотой его использования, а поскольку он встроен в JavaScript, вам больше не нужен фреймворк или библиотека для его использования.
Посмотрите это на YouTube
Структура файла
/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-файл.
Метод AJAX
В вашем файле /js/init.js
вы можете использовать jQuery для ссылки на метод AJAX.
ПРИМЕЧАНИЕ: Убедитесь, что тег jQuery добавлен в ваш файл index.html
выше.
$(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
.
Теперь событие on-click для элемента .country-list
должно принять динамический список и дать вам возможность установить текстовое поле на основе выбора.
Метод API Fetch
ПРИМЕЧАНИЕ: Этот метод использует встроенные функции 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
.
Теперь событие on-click для элемента .country-list
должно принять динамический список и дать вам возможность установить текстовое поле на основе выбора.
Заключение
Лично мне нравится Fetch API. Я так долго использовал jQuery, что забыл, как использовать Vanilla JS, но когда я смог вернуться к нему, я почувствовал, что он лучше, поскольку он быстрее и занимает гораздо меньше места на моих серверах.
Вы можете использовать любой из них в зависимости от ваших потребностей. Fetch возвращается к Vanilla JS и дает вам гораздо больше гибкости, если вы планируете использовать другие фреймворки помимо jQuery (React, Vue и т.д.).