Last active
February 27, 2018 20:12
-
-
Save kuzminT/b6d4c455c450cef633c02569fb5217d4 to your computer and use it in GitHub Desktop.
Ajax with vanilla js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
let xhttp = new XMLHttpRequest(); | |
function onload (e) { | |
// Можно работать напрямую с event и получать данные напрямую оттуда | |
// console.log(e.target.response); | |
// Или же обращаться к ответу через this | |
console.log(this.response); | |
}; | |
xhttp.addEventListener('load', onload); | |
xhttp.open('get', 'test.php', true); // параметры: метод, адрес запроса, синхронный/асинхронный | |
xhttp.responseType = 'json'; // Чтобы получить из json уже готовый объект, нужно явно указывать responseType. | |
// Иначе придётся использовать JSON.parse(). На данный момент данный параметр корректно работает в большинстве современных | |
// браузерах, но возможны проблемы, связанные с Internet Explorer | |
// xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); // отправка данных | |
// в специально подготовленной ссылке - xhttp.send('name=' + encodeURIComponent(name)); | |
// xhttp.setRequestHeader('Content-type', 'application/json; charset=utf-8'); | |
// xhttp.setRequestHeader('Content-type', 'application/xml'); | |
xhttp.send(); // Отправка сообщения | |
/** | |
Полезные ссылки по теме: | |
https://developer.mozilla.org/ru/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest | |
https://www.sitepoint.com/guide-vanilla-ajax-without-jquery/ | |
http://easy4web.ru/?p=393 - работа с xml | |
**/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment