The preface
What is the Ajax
?Ajax is a technique for updating parts of a web page without having to reload the entire page.
Ajax is short for asynchronous JavaScript and XML.
At the heart of Ajax technology is the XMLHttpRequest object, or XHR. The ability to retrieve new data from the server asynchronously means that the user clicks a button to request data and can retrieve new data to update the current page without having to refresh the page.
XMLHttpRequest object ๐MDN transfer
IE5 was the first browser to introduce the XMLHttpRequest object.
But it’s 2020 and IE7+ supports native XHR objects. Create it directly using the XMLHttpRequest() constructor.
var xhr = new XMLHttpRequest(); The # open() method starts a request ready to be sent. The request has not been sent yet# The first argument specifies how to send the request. This string is case insensitive, but usually uses uppercase letters,"GET"and"POST" The second argument is the URL, which can also be an absolute path relative to the current page where the code is executingThe third parameter is a Boolean value that indicates whether to send the request asynchronously or nottrueIs sent asynchronouslyxhr.open("get"."ex.txt".false); / / synchronize # post request is as followsxhr.open('post'."login.php".true) xhr.setRequestHeader("Content-Type"."application/x-www-from-urlencoded") var form = $('#user-info').serialize(); The serialize() method creates a URL-encoded text string by serializing form values. // FirstName=Mickey&LastName=Mouse xhr.send(form) // Send serialized form data # send() sends the request, which is then dispatched to the serverxhr.send(null); # Abort () can also be used to abort an asynchronous request before receiving a response. First thing, check the status property to make sure the response has returned successfully. The HTTP flag code is200As a successfulAt this point, the content of the responseText property is ready and the responesXML is accessible with the status code304Indicates that the requested resource has not been modified. Use the buffered version directly in the browser. xhr.onreadystatechange = function(){ if(xhr.readyState ==4) {// All response data has been received and can be used on the client if((xhr.status >=200 && xhr.status < 300) || xhr.status ==304) { console.log('Request successful', xhr.responseText) }else{ console.log('Request failed') } } } # readyState State value# 0Uninitialized, the open() method is not called# 1Start, call open(), not send()# 2Send, call send(), no response received# 3Received. A partial data response has been received# 4Complete. All response data has been received and can be used on the client Copy the code
XHR timeout setting
IE8 adds a timeout attribute to the XHR object that indicates how many milliseconds the request has to wait for the response to terminate.
var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function(){ if(xhr.readyState ==4) {// All response data has been received and can be used on the client try { if((xhr.status >=200 && xhr.status < 300) || xhr.status ==304) { console.log('Request successful', xhr.responseText) }else{ console.log('Request failed') } } catch (ex){ // Handled by the onTimeout event } } } xhr.open("get"."ex.txt".true); / / asynchronous xhr.timeout = 1000 xhr.ontimeout = function(){ console.log('Request timed out') } xhr.send(null); Copy the code
The difference between GET and POST requests (interview frequency)
Both of them
Hypertext Transfer Protocol (HTTP)
The request method is the request-response method between the client and the server.
GET
– Requests data from the specified resource.Query string (name/value pair)
Is the GETSent from the requested URL
POST
– Submits data to be processed to the specified resource.Query string (name/value pair)
Is in the POSTSent in the HTTP message body of the request
.
Difference between contrast GET POST Back button/refresh harmless The data will be resubmitted (browsers should inform users that the data will be resubmitted). bookmarks Bookmark Do not bookmark The cache Can be cached Can’t cache The encoding type application/x-www-form-urlencoded Application/x – WWW – form – urlencoded or multipart/form – the data. Use multiple encoding for binary data. history Parameters are retained in browser history. Parameters are not saved in browser history. A limit on the length of data Yes. When sending data, the GET method adds data to the URL; URL length is limited (maximum LENGTH of URL is 2048 characters). Unlimited. Restrictions on data types Only ASCII characters are allowed. There is no limit. Binary data is also allowed. security GET is less secure than POST because the data sent is part of the URL. Never use GET! When sending passwords or other sensitive information. POST is more secure than GET because parameters are not saved in browser history or Web server logs. visibility The data is visible to everyone in the URL. The data is not displayed in the URL.
When we talk about Ajax, we have to say cross domain.
So what is cross-domain?
A document or script in one domain attempts to request a resource in another domain. Contains the following:
- Resource jump: A link, redirect, form submission
- Resource embedding:
<link>, <script>, <img>, <frame>
And other dom tags, as well as style background: URL (), @font-face() and other external links of the file- Script requests: JS-initiated Ajax requests, dom and JS object cross-domain operations, etc
We often encounter narrowly defined cross-domain request scenarios that are restricted by the browser’s same-origin policy.
So what is the same origin policy?
The ๐ same origin policy is an important security policy that restricts how a ๐ Origin document or the scripts it loads can interact with resources from another source. It can help block malicious documents and reduce the number of vectors that can be attacked.
Cognate definition: Two urls are cognate if they have the same ๐protocol, ๐port (if specified), and ๐host.
The purpose of the same origin policy is to ensure the security of user information and prevent malicious websites from stealing data.
Limit the following behaviors:
- Cookie, LocalStorage, and IndexDB cannot be read
- A Cookie is a small piece of information written by a server to a browser that can only be shared by web pages of the same origin. However, the level 1 domain name of the two pages is the same, but the level 2 domain name is different, and the browser allows the setting
document.domain
Share the cookies.- DOM and Js objects are not available
- AJAX requests cannot be sent
Several solutions across domains
The json cross-domain
: Only one get request can be implemented.
- Implementation principle: Script, link, img tags can load static resources, browsers allow.
- Document. domain + iframe cross-domain: This scheme applies only to cross-domain scenarios where the primary domain is the same and the subdomains are different.
- Implementation principle: two pages through JS forced document.domain as the base of the primary domain, to achieve the same domain.
- location.hash + iframe
- Window. name + iframe cross domain
- PostMessage cross-domain
Cross-domain Resource Sharing (CORS)
: mainstream cross-domain solutions.Nginx agents cross domains
- Cross-domain principle: The same Origin policy is a security policy of the browser, not a part of the HTTP protocol. The server invokes the HTTP interface only using THE HTTP protocol, and does not execute JS scripts. There is no need for the same origin policy, so there is no crossing problem
- Nginx configure a proxy server (domain name and domain1 the same, different port) as a jumper, reverse proxy access to domain2 interface, and can incidentally modify the cookie in the domain information, convenient for the current domain cookie writing, cross-domain login.
Nodejs middleware proxies cross domains
- Node middleware implements cross-domain proxy, which is roughly the same as nginx. It starts a proxy server to forward data. It can also modify the domain name in the cookie in the response header by setting the cookieDomainRewrite parameter to implement cookie writing in the current domain, facilitating interface login authentication.
The WebSocket protocol is cross-domain
- WebSocket Protocol is a new protocol for HTML5. It implements full duplex communication between browser and server, and allows cross-domain communication. It is a good implementation of server push technology. ๐ https://socket.io/
๐Stop asking me cross-domain questions
๐Common Cross-domain solutions at the front end (full)
This article is formatted using ๐ MDnice