English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Ajax is a technology that allows additional data to be requested from the server without reloading the page, thus enabling web pages to have a better user experience. The core of Ajax technology is the XMLHttpRequest object (XHR). This article starts with XHR to understand the characteristics of Ajax technology, and then briefly discusses cross-domain and Comet technologies and summarizes them.
Basic Usage of XMLHttpRequest
The XMLHttpRequest object has two commonly used methods: open and send. The open method is used to initiate an HTTP request, but it does not actually send the HTTP request. The open method accepts3parameters, respectively representing the HTTP method of the request, the URL of the request, and whether it is asynchronous. The second method send of the XHR object is used to send the request started by open. The send method takes1parameters, representing the HTTP method of the request, the URL of the request, and whether it is asynchronous. The second method send of the XHR object is used to send the request started by open. The send method takes/api/data to send a GET request and it is sent asynchronously, that is, this request will not block the execution of other js code in the page.
var xhr = new XMLHttpRequest() xhr.open("get", "/api/data", true) xhr.send(null)
The response data obtained by the request will be automatically filled into the properties of the XHR object, mainly including the following4properties:
* responseText: The text of the response body
* responseXML: If the response content type is "text/xml" or "application/xml", this property will contain the XML DOM document of the response data
* status: The HTTP status code of the response, which can generally be considered as the HTTP status code200 is considered a successful indicator
* statusText: The description of the HTTP status
XHR objects have1readyState properties that record the possible experiences of the object from creation to receiving the response data5types, the possible values of readyState are as follows:
0: The open() method has not been called to initialize the request
1: The open() method has been called but the send() method has not been called
2: The send() method has been called but the response has not been received
3: Part of the response data has been received, and some data has not been received
4: All the response data has been received, that is, the response is complete, and the data is complete
the readystatechange event is triggered when the readyState changes from one value to another, and when this event is triggered, you only need to check the value of readyState in the event handler to see if it is4when its value is4at that time, you can perform subsequent processing on the response data. The handler for the readystatechange event must be specified before calling the open() method to ensure cross-browser compatibility. The following is a simple example.
var xhr = new XMLHttpRequest() xhr.onreadystatechange = function() { if (xhr.readyState === 4) { console.log(xhr.status, xhr.responseText) } } xhr.open("get", "/api/data", true) xhr.send(null)
The XHR object provides the setRequestHeader() method to set custom HTTP header information for the request. This method takes two parameters, the field to be set and the value of that field. setRequestHeader() can only be set successfully after calling open() to start a request and before calling send() to send the request. After the request receives a response, the getResponseHeader() method can be used to obtain the HTTP header information of the response, which takes1parameter, that is, the field name to be obtained. And through getAllResponseHeaders() you can get a long string composed of all the header information. Below is a simple example.
var xhr = new XMLHttpRequest() xhr.onreadystatechange = function() { if (xhr.readyState === 4) { console.log(xhr.status, xhr.responseText) console.log(xhr.getResponseHeader('SomeKey')) console.log(xhr.getAllResponseHeaders()) } } xhr.open("get", "/api/data", true) xhr.setRequestHeader("SomeKey", "SomeValue") xhr.send(null)
FormData
XMLHttpRequest 2level defines the FormData type as serializing form, creating data in the same format as the form, and providing convenience for XHR transmission. FormData provides the append() method to directly add data, which takes two parameters: key and value. The FormData constructor can be passed without parameters, or directly传入1elements. After passing the form element, the data of the form element will be used to pre-fill key-value pairs into the FormData object. Below is a simple example.
var form = document.getElementById('myForm') var data = new FormData(form) data.append('someKey', 'someValue') var xhr = new XMLHttpRequest() xhr.onreadystatechange = function() { if (xhr.readyState === 4) { console.log(xhr.responseText) } } xhr.open('post', '/api/upload', true) xhr.send(data)
Cross-Origin Resource Sharing
When implementing Ajax communication through XHR, a limitation will be encountered, that is, cross-domain security policy. The cross-domain security policy restricts 'same domain, same port, same protocol', and when XHR wants to access resources outside of the restriction, it will trigger a security error. CORS (Cross-Origin Resource Sharing)-Origin Resource Sharing, Cross-Origin Resource Sharing, which is an idea to communicate between browsers and servers using custom HTTP headers to decide the success or failure of requests or responses. It requires both browsers and servers to support it to achieve normal access. Currently, most browsers have supported CORS, so writing code is almost the same as accessing same-origin resources, just that the URL is represented in an absolute path. Therefore, the key to realizing cross-domain access is still on the server, and the specific implementation will not be discussed in detail in this article. Below is a simple example of front-end JavaScript.
var xhr = new XMLHttpRequest() xhr.onreadystatechange = function() { if (xhr.readyState === 4) { console.log(xhr.responseText) } } xhr.open('get', 'http://www.otherserver.com/api/data', true) xhr.send(null)
JSONP
JSONP (JSON with padding) is a method to achieve cross-domain resource access by applying JSON. JSONP consists of two parts: a callback function and JSON data. As mentioned before, XHR requests may encounter cross-domain security policy restrictions, but the script tag in HTML does not have this restriction. We can reference js files from different domains through the script tag. JSONP takes advantage of this by dynamically creating a script element, pointing the src to the URL of another domain to load resources from other domains, and then processing the loaded data through a callback function. Here is a simple example.
function handler(res) { console.log(res) } var script = document.createElement('script') script.src = 'http://www.otherserver.com/api/data/?callback=handler' document.body.insertBefore(script, document.body.firstChild)
The above code specifies the src of the dynamically created script element to be a URL under another domain./api/Then specify the callback function as handler. After the script is inserted into the DOM, it will load data from the corresponding URL, parse the obtained JSON data into an object, and call handler to process it.
JSONP is a simple method to achieve cross-domain access, but it also has some security issues, such as receiving a malicious script from the URL of another domain in the response. JSONP also has a problem that the script tag references js, and since json is supported by js, it can also be referenced. Therefore, when requesting URLs from other domains, it is necessary to confirm that it responds in json format rather than XML.
Comet
Ajax is a technology for requesting data from the server to the web page, while Comet is the opposite, which is a technology for pushing data from the server to the web page, suitable for applications with 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, which is very simple in thought, that is, the client uses a timer to send Ajax requests to the server at certain time intervals to see if there are any data updates, and this time interval is usually very small. Long polling is also the client continuously sending requests to the server, but differently, the client does not need to send requests at fixed time intervals, but to initiate1requests to the server, after which the HTTP connection between the client and the server remains open until the server has data updates, and then it sends data to the client through this connection and closes this HTTP connection. After the connection is closed, the browser initiates a new connection to continue the process. Compared to short polling, long polling reduces the number of HTTP connections, but if the HTTP connection remains open for a long time, it also occupies the server's resources.
The second way to implement Comet is based on HTTP streaming, where the client initiates1HTTP connection, keeping this connection open throughout, and the client periodically fetches data from the server to check for updates through this connection.
SSE
SSE (Server-Sent Events)-Send Events), Server-Sent Events, is a browser API for implementing Comet interaction, supporting polling as well as HTTP streaming. The SSE API is used to create a unidirectional connection to the server, through which the server can send an arbitrary number of data to the client. The MIME type of the server response is text/event-stream. Below is a simple example of the JavaScript API for SSE.
var source = new EventSource("/api/events) source.onmessage = function(event) { console.log(event.data) }
As shown in the above code, to book an event stream to the server and obtain the data sent by 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 the event.data in string format. The EventSource object will maintain an active connection with the server, and it will reconnect if the connection is interrupted. To truly disconnect the connection, you can call 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 also has another2There are two events: open and error. The open event is triggered when the connection is established, and the error event is triggered when the connection cannot be established.
Web Sockets
Web Sockets is a channel for full-duplex bidirectional communication with the server. Web Sockets is not applicable to HTTP protocol, while the Ajax and Comet mentioned earlier both use HTTP protocol. Due to the length of the article, this article does not discuss Web Sockets.
Summary
Ajax can request data from the server without reloading the page, enhancing the user experience of web pages. When implementing Ajax technology with XHR, it may encounter cross-domain security policy restrictions. To solve cross-domain problems through CORS, cooperation is required between both the browser and the server. JSONP is a 'trick' for implementing cross-domain access, but it also has some problems. Comet extends Ajax, allowing the server to push data to the browser in real-time. However, from the implementation perspective, whether it is polling or HTTP streaming, the browser initiates the request connection to the server first. Full-duplex bidirectional communication of Web Sockets also has its characteristics. We can continue to learn about it when we have time.
That's all for this article. I hope the content of this article can bring some help to everyone's learning or work, and I also hope to get more support for the Yelling Tutorial!
Declaration: The content of this article is from the Internet, and the copyright belongs to the original author. The content is contributed and uploaded by Internet users spontaneously. This website does not own the copyright, has not been manually edited, and does not assume any relevant legal responsibility. If you find any content suspected of copyright infringement, please send an email to: notice#w.3If you find any infringing content, please report by email to: notice#w, replacing # with @, and providing relevant evidence. Once verified, this site will immediately delete the content suspected of infringement.