...

Программа ajax что это

Introduction to Ajax

Asynchronous JavaScript And XML

4 min read
Sep 13, 2020

What’s Ajax

A jax stands for Asynchronous JavaScript And XML. It’s a term coined by Jesse James Garrett in his paper Ajax: A New Approach to Web Applications. It’s not a single technology, but rather a design paradigm for web applications.

Before Ajax, when a web page is loaded in the user’s browser, the server cannot change it anymore. This is similar to you buy some merchandise in the real world. After the purchase, you can do whatever you want with the merchandise and it’s totally up to you. But the merchant cannot change it because they no longer own it. When you want to make more purchases (i.e. visit another page), you go to the store again.

With Ajax, the server can control the page even after it’s loaded in the user’s browser. It can ask the client to make requests to the server in the background using JavsScript and process the response data. One common use case is to partially update the page asynchronously without requiring a full refresh.

How to use Ajax

The core of it is the use of XMLHttpRequest , which is a living standard supported in all browsers. Below is a simple example:

var xhr = new XMLHttpRequest();
xhr. onreadystatechange = function() // callback function to handle response
if (this.readyState == 4 && this.status == 200) var rt = this.responseText;
// do sth
>
>
xhr.open('GET', '/foo.txt');
xhr.send();

In the above example, a XMLHttpRequest object is first created. Then a callback function is assigned to it for handling server response.

XMLHttpRequest.readyState equals to 4 means the request is completed. Below is the list of all possible values²:

  • 0 (UNSENT): The object has been constructed.
  • 1 (OPENED): The open() method has been successfully invoked. During this state, request headers can be set using setRequestHeader() and the fetch can be initiated using the send() method.
  • 2 (HEADERS_RECEIVED): All redirects (if any) have been followed and all HTTP headers of the response have been received.
  • 3 (LOADING): The response’s body is being received.
  • 4 (DONE): The data transfer has been completed or something went wrong during the transfer (e.g. infinite redirects).

The XMLHttpRequest.status attribute returns the response status code. 200 means the request has succeeded.

The XMLHttpRequest.open(method, url [, async = true [, username = null [, password = null ]]]) method is for initializing a request. The first two arguments are the request method and request url. The request url can be a full or partial url. There is also a third optional argument to specify whether it’s async or not. The default is async, meaning the user can interact with the page while waiting for the response to arrive. There are two other optional arguments for authentication purposes. For details see the doc.

The XMLHttpRequest.send([body = null]) method initiates the request. The body argument is optional and provides the request body. It will be ignored if the request method is GET or HEAD . It can be any data but a common use case is query string:

xhr.send("age=18&firstname=K");

Note if you need to POST data like an HTML form⁴, you need to add an HTTP header before calling send :

xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

To handle the response, there are two major ways⁴:

  1. XMLHttpRequest.responseText – get the response data as a string
  2. XMLHttpRequest.responseXML – get the response data as an XMLDocument object which you can traverse with JavaScript DOM functions.

There are other advanced features such as monitoring progress with event handlers and uploading files⁵.

Security considerations

For security reason (i.e. Same-Origin-Policy), if the request url is on a different origin (see definition), the request will fail when you call send and you will see an error like this:

Access to XMLHttpRequest at ‘https://www.medium.com/’ from origin ‘https://medium.com’ has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.

Sometimes, even you are using the same origin url, you might still see some errors related to Content Security Policy like:

Refused to connect to ‘https://www.yourdomain.com/’ because it violates the following Content Security Policy directive: “connect-src …

In such cases, you need to examine your CSP header to see if the origin is blocked.

One last thing to point out is cross-origin requests are possible by using CORS. If the server is configured to allow requests from the request origin, XMLHttpRequest will work.

Common pitfalls

  1. Without Cache-Control: no-cache , the browser will cache the response and never re-submit the request⁴.
  2. Be aware of race conditions if you make your XMLHttpRequest object global⁴.
  3. While XMLHttpRequest provides some powerful features that make Ajax web applications possible, it’s being gradually replaced by the modern Fetch API standard⁷.

See also

  1. Ajax: A New Approach to Web Applications
  2. XMLHttpRequest Specification
  3. https://developer.mozilla.org/en-US/docs/Web/Guide/AJAX
  4. https://developer.mozilla.org/en-US/docs/Web/Guide/AJAX/Getting_Started
  5. https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest
  6. https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest
  7. https://developer.mozilla.org/en-US/docs/Glossary/AJAX
  8. https://medium.com/beginners-guide-to-mobile-web-development/the-fetch-api-2c962591f5c
  9. https://www.w3schools.com/xml/ajax_intro.asp

Who am I

I am a software engineer working at Facebook. If you would like to contact me, below is my email address:

secuitysev [at] gmail [dot] com

Что такое AJAX?

img

При изучении принципов написания программного кода вы, вероятно, встречались с термином AJAX и задавались вопросом, что же он значит. Что это – язык программирования, платформа или приложение? На самом деле ничего из перечисленного, но к концу прочтения этой статьи вы будете знать, что же такое AJAX (Asynchronous Javascript and XML – асинхронные сценарии JavaScript и XML).

AJAX

История AJAX

До конца 1990-х годов большинство веб-сайтов могли выдавать в качестве результата только полные веб-страницы при посещении страницы на сайте. Иначе говоря, для того, чтобы перезагрузить какие-либо отдельные данные, вам необходимо было перезагрузить всю страницу.

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

В 1996 году Microsoft представила тег iframe для Internet Explorer, который позволял браузеру асинхронно извлекать данные в фоновом режиме. Это был шаг в верном направлении на пути к современным веб-приложения.

В 2004 году Google добавила в Gmail функцию, позволяющую получать данные в фоновом режиме, а в 2005 году они сделали то же самое и для Google Maps.

Технологии Google и Microsoft позволяли разработчикам получать данные с веб-сервера с помощью JavaScript без необходимости перезагружать страницу. В 2005 году Джесси Джеймсон Гарретт в своей статье (о том, как Google добились такого результата) назвал эту технологию AJAX. Эта технология быстро стала одним из самых популярных способов создания веб-приложений.

А теперь, когда вы узнали немного из истории AJAX, давайте посмотрим, как это работает.

Как работает AJAX?

Что делает работу AJAX возможной, так это встроенный в веб-браузер объект XMLHttpRequests (XHR). Этот объект поддерживают все современные браузеры, включая:

Большинство библиотек JavaScript, которые используют AJAX, помещают этот объект в пользовательский код для того, чтобы упростить его использование разработчиками, но мы рассмотрим, как AJAX работает в обычном JavaScript.

Первый шаг – создать переменную, которая будет создавать для вас экземпляр объекта XMLHttpReaquests в JavaScript. Ниже приведен пример:

const request = new XMLHttpRequest();

Поскольку мы хотим использовать эти данные в дальнейшем, например, хотим распечатать их на веб-странице, то мы добавим к этому запросу получатель запроса, который сообщит нам, когда наш запрос закончит обрабатываться и получит нужные данные.

Как можно понять из самого термина, запросы AJAX выполняются асинхронно. Это значит, что код JavaScript продолжает работать после отправки запроса и не ждет ответа. Прикрепив получатель запросов, мы можем перехватить ответ, когда он будет готов. Сделаем мы это вот так:

function requestListener() < console.log(this.responseText); >request.addEventListener("load", requestListener);

Выше у нас есть функция, которая выводит ответ на консоль JavaScript, которую мы можем получить из атрибута responseText объекта XMLHttpRequests . Затем мы присоединяем эту функцию к событию load нашего запроса.

Следующий шаг – используем этот объект для отправки запроса к серверу с помощью метода open объекта XMLHttpRequests . Метод open принимает два параметра. Первый параметр – это используемый метод запроса. Ниже приведены несколько наиболее распространенных методов:

  • GET: этот метод используется для извлечения данных и является наиболее распространенным.
  • POST: этот метод отправляет данные запрошенному ресурсу и чаще всего используется для создания новых записей или для входа в систему.
  • PUT: этот метод заменяет текущие представления данных измененными, которые были отправлены в запросе.
  • PATCH: этот метод обычно используется для обновления части данных в запрошенном ресурсе.
  • DELETE: этот метод используется для удаления определенного ресурса.

Второй параметр, который передается методу open , – это запрашиваемый ресурс. Мы будем использовать страницу с веб-сайта example.org и использовать запрос GET для простого получения данных. Вот так это будет выглядеть:

request.open("GET", "http://www.example.org/example.txt");

Последний шаг – фактическая отправка запроса на удаленный ресурс с помощью метода send объекта XMLHttpRequests . Ниже приведен пример:

request.send();

Если мы используем метод POST, PUT или какой-либо другой метод, который обновляет ресурс, то этот метод мы вызываем с параметром, содержащем данные, которые мы отправляем:

request.send(OUR_DATA_VARIABLE)

В нашем случае мы только извлекаем данные, поэтому, как только мы выполним этот код, на консоли нашего веб-браузера выведется содержимое http://example.org/example.txt .

Данный пример помогает объяснить то, как работает AJAX, но на самом деле технология AJAX имеет куда более продвинутые функциональные возможности.

Для чего нужен AJAX?

Что вы должны были вынести из приведенного выше примера, так это то, что все функции кода загружаются на одной странице. Действительно, сначала загрузится веб-страница с нашим кодом JavaScript, затем он выполнится, и после он распечатает результаты запроса.

С таким же успехом можно было прикрепить приведенный выше код к функции, которая выполняется при нажатии кнопки. Это бы означало, что каждый раз при нажатии кнопки, будет выполняться код, отправляться запрос, и результаты будут выводиться на консоль без загрузки новой страницы.

И эта магическая технология изменила подход к веб-разработке. С появлением AJAX большая часть веб-разработки переместилась на внешний интерфейс приложения – часть, которая работает в браузере. Вы наблюдаете то, как работает AJAX ежедневно и даже не подозреваете об этом.

Когда вы заходите на современный веб-сайт, перед вами появляется форма. Вы вводите свои учетные данные и нажимаете кнопку «Войти». Индикатор загрузки может вращаться в течение нескольких минут, но если вы обратите внимание, то заметите, что страница на самом деле никогда не перезагружается. Все, что вы сделали, это просто отправили свое имя пользователя и пароль на сервер с помощью AJAX.

Индикатор загрузки нужен только для отвода глаз, пока запрос выполняется, независимо от того, ввели ли вы верные учетные данные или нет. Если ваши учетные данные верны, то ваша домашняя страница загружается, скорее всего, из другого запроса AJAX.

Большинство запросов AJAX в JavaScript не загружают целые веб-страницы, как в нашем примере. Данные отправляются и извлекаются в формате JSON, для представления данных используется текстовый формат, а для форматирования этих данных в формате HTML и их печати на странице используется дополнительный код JavaScript. Например, данные, которые отправляются для входа на веб-сайт, в формате JSON будут выглядеть так:

Как только учетные данные будут проверены, файл JSON, содержащий минимальный объем данных для отображения панели инструментов, будет отправлен обратно в браузер. AJAX в сочетании с JSON не только наделяет современные веб-страницы способностью быстро реагировать на действия пользователей, но и экономит пропускную способность, отправляя только необходимые данные для создания веб-страницы.

What Is AJAX and How Does It Work?

What Is AJAX and How Does It Work?

The term AJAX stands for Asynchronous JavaScript and XML. Understanding AJAX is essential for web developers since it is commonly used in popular web applications like Google Maps, Gmail, Facebook, and Twitter.

This article covers everything you need to know about AJAX, including its definition, practical examples, how to learn the technique, and its pros and cons.

What Is AJAX?

AJAX stands for Asynchronous JavaScript and XML. It is a set of web development to build more responsive websites and applications. AJAX allows web pages to update their content without users having to reload the page.

AJAX is derived from JavaScript’s function to allow for a more interactive experience. JavaScript creates, adds, and manages dynamic structure by monitoring which content requires real-time updates while a visitor is accessing a website.

Meanwhile, Extensible Markup Language (XML) transports the data between the web server and the browser. Aside from XML, other formats like plain text and JSON are frequently used for exchanging data.

JavaScript and Extensible Markup Language work together under AJAX to ensure the web page content is updated asynchronously. In other words, with AJAX, site content can be updated without reloading the entire page.

How Does AJAX Work?

AJAX comprises the following technologies:

  • XHTML and CSS – for presenting the information.
  • The Document Object Model (DOM) – for the dynamic display data and its interaction.
  • XML,HTML, and XSLT – for data interchange and manipulation. However, many developers have replaced XML with JSON since it originated from JavaScript.
  • XMLHttpRequest object – allows asynchronous communication with the web server.
  • JavaScript – the programming language that links all these web technologies.

The general principles of AJAX are simple. However, having existing technical knowledge will help you understand the workflow faster.

Take a look at the diagram and table below to compare the conventional model vs the AJAX model of a web application.

Diagram:

Comparison table:

Practical Examples of AJAX

An example of AJAX is the Google Autocomplete feature. This feature offers keyword suggestions, helping users complete their search query when typing into the search bar. The changes happen in real-time, but the web page remains the same.

AJAX allows the data exchange and presentation layer to work simultaneously without interfering with each other’s functions.

This was not the case in the early 90s when this new technology was yet to be introduced. You had to reload Google for a new recommendation to appear on your screen.

Here are more helpful examples of the AJAX method in our everyday lives:

  • Voting and rating systems – once you click a rate or vote button, the website automatically updates the calculation without refreshing the page.
  • Chat rooms – some websites implement a built-in customer support chat room on their main page. Using AJAX, you can talk with a customer support representative while exploring the website. The web page won’t need to reload whenever you send or receive a new message.
  • Social media – many social media applications, such as Twitter use AJAX to update their users’ timelines. The system will request and retrieve data from the server when you post a new tweet. Then, it will display the new tweet on top of the timeline.

Should I Learn AJAX?

Learning AJAX is relatively easy, especially if you have prior knowledge of HTML, XML, JavaScript, and CSS.

For advanced developers, understanding AJAX can only take one or two hours since the technique implements the development skills you have already mastered.

If you’re a beginner, it usually takes an hour to learn the fundamental principles and a day or two to understand XMLHttpRequest syntaxes – the key to AJAX.

Whether you’re an advanced or new developer, we recommend practicing using real-world examples to master the technique.

Here are four steps to learn AJAX:

  1. Familiarize yourself with JavaScript, HTML, XML, and CSS – these languages are prerequisites for learning AJAX.
  2. Research how AJAX is used – learn how AJAX is applied to web apps and the techniques used to develop them. For example, study Google Maps, which runs AJAX to retrieve new map data.
  3. StudyjQuery – many web applications that use AJAX also run jQuery. Therefore, we recommend learning the basics of jQuery to write advanced AJAX applications.
  4. Create a project using AJAX – put your development knowledge and skills into practice.

Like other popular web development topics, AJAX has many learning resources. In this section, we have listed the five best online courses to learn AJAX:

  • Learn JavaScript AJAX in 1 hour by Udemy – this course will teach you how to use AJAX to run GET and POST requests, create an interactive experience, and build dynamic content. It consists of an hour-long video, and the price is $14.99.
  • JavaScript and AJAX: Integration Techniques by LinkedIn Learning – in this course, you will learn the basic principles of AJAX and how to incorporate XML, jQuery, and JSON. This course costs $34.99.
  • Intro to AJAX by Udacity – this free course will teach you how to make asynchronous requests using jQuery’s AJAX functionality and user data APIs. You will also get to build a web application to practice your skills.
  • AJAX Introduction by W3Schools – in this free course, you will learn about the basics of AJAX. In addition, W3Schools provides quizzes and practices in every section to test your knowledge.
  • AJAX Tutorial by Tutorials Point – this free course will teach you the basic principles of AJAX and how to apply it. Tutorials Point also recommends other courses related to the topic to help you understand AJAX better.

AJAX is a universally used technique and an essential part of front-end development, making it one of the most in-demand skills. According to Glassdoor, the average salary of a front-end developer is around $102,000/year.

Developers with less than one year of experience earn about $100,000/year. On the other hand, senior front-end developers may receive an average salary of over $120,000/year.

AJAX Pros and Cons

Before using AJAX, consider its pros and cons:

Pros

  • Allows a browser to update bits of content without reloading or opening a new page.
  • Reduces server traffic by allowing web applications to render without data.
  • Uses less bandwidth since it fetches little bits of content.
  • Lets browsers make asynchronous calls to the web server without reloading the whole page.
  • The XMLHttpRequest object in AJAX establishes an independent connection between a website server and the client-side machine.
  • Creates responsive interactions. Mouse movements that aren’t user clicks can also trigger events.

Cons

  • If your browser doesn’t support or enable JavaScript, it will not load web pages using AJAX properly.
  • Anyone can view the source code of a web application developed using AJAX, making it less secure.
  • AJAX works asynchronously. Therefore, some page information may not correspond to a newly loaded one.
  • When a user hits the back button on their browser, they may not return to the previous state of the page. Successive AJAX requests are not saved to the browser’s history.
  • Debugging a web page built using AJAX may be difficult.
  • Multiple server requests consume more data.

Suggested Reading

Conclusion

AJAX is a collection of web development techniques primarily used to send and receive data from a server asynchronously.

AJAX lets you create a dynamic and interactive experience. It automatically adds new information to the existing page without reloading the entire website.

As the method becomes more popular, there are many job opportunities for web developers with knowledge of AJAX. We have compiled a list of resources to help you learn AJAX, including online courses from Udemy, Linkedin Learning, Udacity, W3Schools, and TutorialsPoint.

In addition, we have explained the pros and cons of building an AJAX application.

We hope this article has helped you understand AJAX better. If you have any questions or suggestions, please leave them in the comments section below.

The author

Domantas leads the content and SEO teams forward with fresh ideas and out of the box approaches. Armed with extensive SEO and marketing knowledge, he aims to spread the word of Hostinger to every corner of the world. During his free time, Domantas likes to hone his web development skills and travel to exotic places.

При подготовке материала использовались источники:
https://medium.com/@sev0/introduction-to-ajax-c262f901bed5
https://wiki.merionet.ru/articles/chto-takoe-ajax
https://www.hostinger.com/tutorials/what-is-ajax

Добавить комментарий