SoFunction
Updated on 2025-03-10

Ajax and Comet technical summary

Ajax is a technology that can request additional data from the server without uninstalling the page, which can give the web page a better user experience. The core of Ajax technology is the XMLHttpRequest object (XHR). This article starts with XHR, understands the characteristics of Ajax technology, and then briefly understands and summarizes cross-domain and Comet technologies.

Basic usage of XMLHttpRequest

There are two commonly used methods for XHR objects, open and send. The open method user initiates an HTTP request, but it does not actually send an HTTP request. The open method receives 3 parameters, respectively indicating the requested HTTP method, the requested URL, and whether it is asynchronous. The second method of the XHR object send is used to send the request initiated by open. The send method receives 1 parameter, indicating the subject data of the HTTP request. If the GET request is sent, such as an HTTP request without subject data, then null is only allowed. If it is a POST request, data that requires POST is passed in. Below is a simple example, which initiates a GET request to /api/data and sends the request asynchronously, that is, the request will not block the execution of other js code in the page.

var xhr = new XMLHttpRequest()
("get", "/api/data", true)
(null)

The response data obtained by the request will be automatically filled into the properties of the XHR object, mainly with the following 4 properties:

* responseText: response body text
* responseXML: If the response content type is "text/xml" or "application/xml", this property will contain the XML DOM document that will contain the response data.
* status: The HTTP status code for the response. Can HTTP status 200 be regarded as a successful identifier?
* statusText: Description of HTTP status

The XHR object has a readyState property that records the 5 states that the object may experience from creation to receiving the response data. The possible values ​​of readyState are as follows:

0: The open() method has not been called yet to initialize the request

1: The open() method has been called but the send() method has not been called yet

2: The send() method has been called but the response has not been received yet

3: Some response data was received, and some data was not received

4: When all response data is received, the response is completed and the data is complete

When readyState changes from one value to another, the readystatechange event will be triggered. When this event is triggered, you only need to check whether the readyState value is 4 in the event processor. When its value is 4, you can perform subsequent processing on the response data. The readystatechange event specifies that the processor must complete before calling the open() method to ensure cross-browser compatibility. Below is a simple example.

var xhr = new XMLHttpRequest()
 = function() {
 if ( === 4) {
  (, )
 }
}
("get", "/api/data", true)
(null)

The XHR object provides the setRequestHeader() method to set the requested custom HTTP header information. This method receives two parameters, the field to be set and the value of the field. Setting is successful after calling open() to start a request and calling setRequestHeader() before sending the request. After the request is responded, the HTTP header information of the response can be obtained through the getResponseHeader() method. This method receives 1 parameter, that is, the field name to be obtained. And through getAllResponseHeaders(), you can get a long string composed of all header information. Below is a simple example.

var xhr = new XMLHttpRequest()
 = function() {
 if ( === 4) {
  (, )
  (('SomeKey'))
  (())
 }
}
("get", "/api/data", true)
("SomeKey", "SomeValue")
(null)

FormData

XMLHttpRequest Level 2 defines the FormData type to facilitate serializing forms, creating data with the same format as the form, and for XHR transmission. FormData provides the append() method to directly add data, which receives two parameter keys and values. The FormData constructor can pass no parameters, or directly pass 1 form element. After passing in a form element, the data of the form element will be used to pre-fill the FormData object with key-value pairs. Below is a simple example.

var form = ('myForm')
var data = new FormData(form)
('someKey', 'someValue')
var xhr = new XMLHttpRequest()
 = function() {
 if ( === 4) {
  ()
 }
}
('post', '/api/upload', true)
(data)

Cross-domain resource sharing

Implementing Ajax communication through XHR will encounter a limitation, namely, cross-domain security policy. Cross-domain security policies restrict "same domain name, same port, same protocol", and security errors will be raised when XHR wants to access resources outside of the restrictions. CORS (Cross-Origin Resource Sharing), cross-domain resource sharing, its idea is to use custom HTTP headers to let the browser communicate with the server, thereby determining the success or failure of the request or response. It requires the browser and server to support it at the same time to achieve normal access. Currently, most browsers already support CORS, so writing code is almost the same as accessing ordinary resources in the same domain, just representing the URL with an absolute path. Therefore, the key to cross-domain is the server. This article will not discuss in depth how to implement it. Below is a simple example of front-end js.

var xhr = new XMLHttpRequest()
 = function() {
 if ( === 4) {
  ()
 }
}
('get', '/api/data', true)
(null)

JSONP

JSONP (JSON with padding) is a method to implement cross-domain resource access using JSON. JSONP consists of two parts: callback function and JSON data. As mentioned earlier, XHR requests will encounter restrictions on cross-domain security policies, but script tags in HTML will not have this limitation. We can refer to js files in different domains through script tags. JSONP exploits this loophole. It dynamically creates script elements, then points src to the URL of other domains to load resources of other domains, and then processes the loaded data through callback functions. Here is a simple example.

function handler(res) {
 (res)
}
var script = ('script')
 = '/api/data/?callback=handler'
(script, )

The above code specifies that the src of the script element created dynamically is /api/data under another domain name, and then indicates that the callback function is handler. After inserting script into the DOM, data will be loaded to the corresponding URL. After completion, the resulting JSON data will be parsed into an object and the handler will be called for processing.

JSONP is an easy way to implement cross-domain access, but there are also some security issues, such as the URL response of other domains requested to give you a piece of malicious code. JSONP also has another problem. The script tag refers to js. Json can also be referenced because it is supported by js. Therefore, when requesting URLs from other domains, you need to confirm whether it responds in json format, rather than XML.

Comet

Ajax is a technology that requests data from a web page to a server, while Comet is the technology that pushes data from a server to a web page, and is suitable for applications with relatively high real-time requirements. There are two ways to implement Comet: long polling and streaming. Before talking about long polling, let’s talk about short polling. Its idea is very simple, that is, the client uses a timer and sends Ajax requests to the server at a certain time interval to see if there is any data update. This time interval is generally very small. Long polling is also the client constantly sending requests to the server. The difference is that the client does not need to send requests continuously at time intervals. Instead, after initiating a request to the server, the HTTP connection between the client and the server remains open until the server has data updates, and then responds to the client through this connection, and then closes the HTTP connection. After closing, the browser initiates a new connection and continues to repeat the previous process. Compared with short polling, long polling initiates fewer HTTP connections, but if the HTTP connection remains open for a long time, it will also occupy the server's resources.

The second way to implement Comet is based on HTTP flow. The client initiates an HTTP connection to the server, keeping the connection open throughout the whole process, and the client periodically obtains data from the server through this connection to view updates.

SSE

SSE (Server-Send Events), a server sends events, is a browser API that implements Comet interaction, supports polling and HTTP streaming. The SSE API is used to create a one-way connection to the server, through which the server can send any amount of data to the client. The MIME type of the server response is text/event-stream. Here is a simple example of SSE's JavaScript API.

var source = new EventSource("/api/events")
 = function(event) {
 ()
}

As shown in the above code, to obtain the data sent by the server by the scheduled event stream to the server, first create an EventSource object, and then process it when the message event is triggered. The data sent by the server is stored in a string. The EventSource object will maintain an active connection to the server, and will reconnect if it is disconnected in the middle. If you want to actually disconnect, you can do so by calling the close() method. The message event of EventSource will be triggered when a new event is received from the server. In addition to the message event, it has two other events, open and error. The open event is triggered when a connection is established, and the error event is triggered when a connection cannot be established.

Web Sockets

Web Sockets is a channel for full-duplex bidirectional communication with the server. Web Sockets does not apply to HTTP protocol, while Ajax and Comet mentioned above both use HTTP protocol. This article will not discuss Web Sockets.

Summarize

Ajax implements requesting data from the server without loading the page, improving the user experience of the web page. XHR implementing Ajax technology will encounter restrictions on cross-domain security policies. Solving cross-domain problems through CORS requires cooperation between the browser and the server. JSONP is a "small trick" to implement cross-domain access, but there are also some problems. Comet has expanded Ajax, allowing the server to push data to the browser in real time, but from the implementation point of view, whether it is polling or HTTP streaming, the browser first initiates a request to the server for connection. Web Sockets' full-duplex two-way communication also has its own characteristics, so you can continue to understand it if you have time in the future.

The above is all the content of this article. I hope that the content of this article will help you study or work. I also hope to support me more!