Home > Web Front-end > Front-end Q&A > What is reverse ajax

What is reverse ajax

青灯夜游
Release: 2022-01-19 18:31:32
Original
1970 people have browsed it

Reverse ajax means that the client does not have to obtain information from the server, and the server will push the relevant information directly to the client. In a standard HTTP Ajax request, data is sent to the server, and reverse Ajax can use certain methods to simulate an Ajax request, allowing the server to send events to the client as quickly as possible.

What is reverse ajax

The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.

Detailed explanation of ajax


##What is ajax

In fact, ajax is already an old technology, and almost no one can use it now. Here I mainly share the underlying things with you, in order to prepare for pretentiousness. interviewer.

What is reverse ajax

ajax stands for "Asynchronous Javascript And XML" (Asynchronous JavaScript and XML), which refers to a web development technology for creating interactive web applications.

By exchanging a small amount of data with the server in the background, AJAX can enable asynchronous updates of web pages. This means that parts of a web page can be updated without reloading the entire page.

The origin of ajax

This technology was applied around 1998.

The first component that allowed client scripts to send HTTP requests (XMLHTTP) was written by the Outlook Web Access team. This component originally belonged to Microsoft Exchange Server and quickly became part of Internet Explorer 4.0[3]. Some observers believe that Outlook Web Access was the first successful business application to use Ajax technology, and it became the lead for many products, including Oddpost's webmail product.

However, it is Google that really makes Ajax well known to the public.

Google uses asynchronous communication in its famous interactive applications, such as Google Discussion Groups, Google Maps, Google Search Suggestions, Gmail, etc. The term Ajax was coined by the article "Ajax: A New Approach to Web Applications", whose rapid spread increased people's awareness of the use of this technology. In addition, support for Mozilla/Gecko makes the technology mature and easier to use.

The principle of ajax

The working principle of Ajax is equivalent to adding an intermediate layer (AJAX engine) between the user and the server. Asynchronousize user actions and server responses. Not all user requests are submitted to the server. Some data verification and data processing are left to the Ajax engine itself. Only when it is determined that new data needs to be read from the server, the Ajax engine will submit the request to the server on its behalf.

Ajax's core consists of JavaScript, The most critical step is to obtain the request data from the server.

Let us understand these objects:

1) XMLHTTPRequest object

One of the biggest features of Ajax is that it can transmit or read and write data to the server without refreshing the page. (also known as no-refresh update page), this feature mainly benefits from the XMLHTTP component XMLHTTPRequest object.

XMLHttpRequest object method description:

What is reverse ajax

XMLHttpRequest object property description:

What is reverse ajax

2) JavaScript

The most amazing language on the front end.

3) DOM Document Object Model

DOM is a set of APIs for HTML and XML files. It provides a structural representation of the file, allowing you to change its content and visibility. Its essence is to establish a bridge between web pages and Script or programming languages. All properties, methods and events that WEB developers can operate and create files are represented by objects (for example, document represents the object "the file itself", table object represents the HTML table object, etc.).

These objects can be accessed from Script by most browsers today. A web page built with HTML or XHTML can also be regarded as a set of structured data. This data is enclosed in DOM (Document Object Model). DOM provides support for reading and writing various objects in the web page.

4) XML

Extensible Markup Language (Extensible Markup Language) has an open, extensible, self-describing language structure, which has become an important part of online data and document transmission. A standard for exchanging data with other applications.

5) Comprehensive

The Ajax engine is actually a relatively complex JavaScript application used to process user requests, read and write servers and change DOM content.

JavaScript's Ajax engine reads information and interactively rewrites the DOM, which allows the web page to be seamlessly reconstructed, that is, changing the page content after the page has been downloaded. This is what we have been doing through JavaScript and DOM. It is a widely used method, but to make a web page truly dynamic, it requires not only internal interaction, but also data acquisition from the outside. In the past, we let users enter data and change the content of the web page through the DOM, but now, XMLHTTPRequest, It allows us to read and write data on the server without reloading the page, minimizing user input.

Ajax separates the interface and application in WEB (it can also be said to separate data and presentation). In the past, there was no clear boundary between the two. The separation of data and presentation is conducive to division of labor and cooperation. It reduces WEB application errors caused by non-technical personnel's modification of pages, improves efficiency, and is more suitable for current publishing systems. You can also transfer some of the previous work burdened by the server to the client, which is beneficial to the client's idle processing power.

Advantages of ajax

Traditional Web application interaction is when the user triggers an HTTP request to the server, and after the server processes it, Returns a new HTML page to the client.

Whenever the server processes a request submitted by the client, the client can only wait idle, and even if it is just a small interaction and only needs to get a very simple piece of data from the server, it must return a complete HTML page, and the user has to waste time and bandwidth to re-read the entire page every time.

This approach wastes a lot of bandwidth. Since each application interaction needs to send a request to the server, the response time of the application depends on the response time of the server. This results in a user interface that is much less responsive than native apps.

Different from this, an AJAX application can only send and retrieve the necessary data to the server. It uses SOAP or some other XML-based Web Service interface, and uses JavaScript on the client to process the response from the server.

Because the data exchanged between the server and the browser is greatly reduced, we can see a more responsive application as a result. At the same time, a lot of processing work can be completed on the client machine that makes the request, so the processing time of the Web server is also reduced.

In fact, in one sentence, I can see the changes without scrolling the entire page. The changes are faster. The client shares the work of the server, and the server pressure is less.

What is reverse ajax

##Disadvantages of ajax

Data and interface exposure, security is not very good .

Detailed explanation of reverse ajax


##What It is reverse ajax
Reverse Ajax (Reverse Ajax) is essentially a concept: being able to send data from the server to the client. In a standard HTTP Ajax request, data is sent to the server. Reverse Ajax can simulate making an Ajax request in some specific ways, so that the server can send events to the client as quickly as possible (low latency communication).

Reverse ajax implementation method

1. Polling

Polling In fact, it is the stupidest way to implement reverse ajax: use javascript to send ajax requests regularly on the client.

setInterval(function() { 
    $.getJSON('events', function(events) { 
        console.log(events); 
    }); 
}, 2000);
Copy after login

In order to obtain server-side events as quickly as possible, the polling interval (the time between two requests) must be as small as possible. The disadvantage of this is obvious: if the interval is reduced, the client browser will issue more requests, many of which will not return any useful data, and this will waste bandwidth and Process resources.

2.PiggyBack (PiggyBack)

PiggyBack is a smarter approach than polling because it will delete all non-essential requests (the ones that don't return data).

It is a semi-active method, which means that the Browser still actively issues the request, but in the response of each request, in addition to the current response, it will also include the information that has occurred since the last request. Changes are sent to the Browser at the same time.

In other words, the update requested will be carried into the response of the next request and sent back. In this way, the Browser feels as if the last request has been updated. But this feeling depends on how often the Browser makes requests to the Server. If the second request is not sent, the last update will not be obtained.

3. Comet (server push)

This is a "server push" technology based on HTTP long connections.

There are two main implementation methods:

1) HTTP Streaming

Embed a hidden iframe in the page, and The src attribute of this hidden iframe is set to a long connection request or an xhr request, and the server will continuously input data to the client.

优点:消息即时到达,不发无用请求;管理起来也相对方便。

缺点:服务器维护一个长连接会增加开销。

实例:Gmail聊天

<script type="text/javascript">
    $(function () {
        (function iframePolling() {
            var url = "${pageContext.request.contextPath}/communication/user/ajax.mvc?timed=" + new Date().getTime();
            var $iframe = $(&#39;<iframe id="frame" name="polling" style="display: none;" src="&#39; + url + &#39;"></iframe>&#39;);
            $("body").append($iframe);

            $iframe.load(function () {
                $("#logs").append("[data: " + $($iframe.get(0).contentDocument).find("body").text() + " ]<br/>");
                $iframe.remove();

                // 递归
                iframePolling();
            });
        })();    
    });
</script>
Copy after login

2)HTTP 长轮询(HTTP Long Polling)

这种情况下,由客户端向服务器端发出请求并打开一个连接。这个连接只有在收到服务器端的数据之后才会关闭。服务器端发送完数据之后,就立即关闭连接。客户端则马上再打开一个新的连接,等待下一次的数据。

优点:在无消息的情况下不会频繁的请求,耗费资源小。

缺点:服务器hold连接会消耗资源,返回数据顺序无保证,难于管理维护。

实例:WebQQ、Hi网页版、Facebook IM。

<script type="text/javascript">
            $(function () {

                (function longPolling() {

                    $.ajax({
                        url: "${pageContext.request.contextPath}/communication/user/ajax.mvc",
                        data: {"timed": new Date().getTime()},
                        dataType: "text",
                        timeout: 5000,
                        error: function (XMLHttpRequest, textStatus, errorThrown) {
                            $("#state").append("[state: " + textStatus + ", error: " + errorThrown + " ]<br/>");
                            if (textStatus == "timeout") { // 请求超时
                                    longPolling(); // 递归调用

                                // 其他错误,如网络错误等
                                } else { 
                                    longPolling();
                                }
                            },
                        success: function (data, textStatus) {
                            $("#state").append("[state: " + textStatus + ", data: { " + data + "} ]<br/>");

                            if (textStatus == "success") { // 请求成功
                                longPolling();
                            }
                        }
                    });
                })();

            });
        </script>
Copy after login

【相关教程推荐:AJAX视频教程

The above is the detailed content of What is reverse ajax. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template