A, Ajax
XHR: Using an XHR object starts with a call to the open() method, which takes three parameters, the request type (“get”,” POST “, etc.), the request URL, and a Boolean value indicating whether the request is asynchronous.
let xhr = new XMLHttpRequest();
xhr.open("get"."example.php".false);
// this line of code can send a synchronous Get request to example.php, without sending the request, just in preparation for sending the request.
Copy the code
xhr.send(null);
// The send() method receives an argument that is sent as the body of the request. If the body of the request is not sent, null must be passed
Copy the code
- After send(), the request is sent to the server for a response. The following attributes of the XHR object are populated with data upon receipt of the response.
- Xhr. readyState == 4(0: uninitialized, 1: opened, 2: sent, 3: accepting, 4: done)
- Changes in readyState from one value to another trigger the readyStatechange event.
xhr.onreadtstatechange=function(){}
Form serialization can use the serialize() function to create the corresponding string.
Second, the cross domain
When the protocol, domain name, or port of a URL request is different from the current page URL, it is called cross-domain
Nonhomologous restriction
- Cookies, LocalStorage, and IndexedDB of non-cognate web pages cannot be read
- DOM of non-homologous web pages cannot be accessed
- Unable to send AJAX requests to non-same-origin addresses
1. Set Document. domain to solve the Cookie problem that cannot read non-same-origin web pages
- Because the browser checks whether two pages are identical through the document.domain property, two pages can share cookies by setting the same Document.domain (this scheme is only applicable to cross-domain scenarios where the primary domain is the same and the subdomain is different).
document.domain = 'test.com';
Copy the code
2. Cross-document communication API: window.postmessage ()
Call postMessage to implement the parent window test1.com to send…
- Data transfer between the page and the new window it opens
- Messaging between multiple Windows
- Page with nested IFrame message delivery
- Cross-domain data transfer for the three scenarios above
// Parent window opens a child window
var openWindow = window.open('http://test2.com'.'title');
// The parent window sends a message to the child window (the first parameter represents what was sent, and the second parameter represents the URL of the window that received the message)
Copy the code
Call the Message event to listen for messages sent by the other party
// Listen for message messages
window.addEventListener('message'.function (e) {
console.log(e.source); // e.ource Window to send messages
console.log(e.origin); // the url to which the message was sent
console.log(e.data); // The message sent by e.ata
},false);
Copy the code
3.JSONP
JSONP is a common way for servers and clients to communicate across sources. The biggest feature is simple to apply, good compatibility (compatible with low version IE), the disadvantage is only support GET request, do not support POST request.
The idea: A web page requests JSON data from the server by adding a <script> element. The server receives the request and returns the data as an argument to a named callback function. ① Native implementation:
<script src="http://test.com/data.php?callback=dosomething"></script>
// make a request to the server test.com with a callback parameter in the query string that specifies the name of the callback function
// Process the data that the server returns from the callback function
<script type="text/javascript">
function dosomething(res){
// Process the obtained data
console.log(res.data)
}
</script>
Copy the code
4. Cross-origin Resource Sharing (CORS)
CORS stands for Cross-Origin Resource Sharing. It is a W3C standard and a fundamental solution for cross-source AJAX requests.
1, common cross-domain request: only need to set access-Control-allow-Origin on the server
2. Cross-domain request with cookie: both the front and back ends need to be set
[Front-end Settings] Determine whether cookies are present based on the xhr.withCredentials field
- Native ajax
var xhr = new XMLHttpRequest(); // Ie8/9 must be window.xdomainRequest compatible
// Set whether cookies are included in the front end
xhr.withCredentials = true;
xhr.open('post'.'http://www.domain2.com:8080/login'.true);
xhr.setRequestHeader('Content-Type'.'application/x-www-form-urlencoded');
xhr.send('user=admin');
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) { alert(xhr.responseText); }};Copy the code
- jQuery ajax
$.ajax({
url: 'http://www.test.com:8080/login'.type: 'get'.data: {},
xhrFields: {
withCredentials: true // Set whether cookies are included in the front end
},
crossDomain: true.// The request header contains additional cross-domain information, but does not contain cookies
});
Copy the code
- axios
axios.defaults.withCredentials = true
Copy the code
- Server Settings
Server support for CORS is mainly through setting access-Control-Allow-Origin. If the browser detects the Settings, Ajax can be allowed to access across domains. 1. Java background
/ * * import packages: import javax.mail. Servlet. HTTP. HttpServletResponse; * Defined in interface parameters: HttpServletResponse Response */
// Domain name that can be accessed across domains: Write the full port (protocol + domain name + port) if there is no port, do not add '/' at the end of the port.
response.setHeader("Access-Control-Allow-Origin"."http://www.domain1.com");
// Allow front-end authentication cookie: After this parameter is enabled, the domain name cannot be '*'. You must specify a specific domain name. Otherwise, the browser will prompt you
response.setHeader("Access-Control-Allow-Credentials"."true");
// Two common custom headers that need to be set on the back end when OPTIONS precheck is prompted
Copy the code
Nodejs background
var http = require('http');
var server = http.createServer();
var qs = require('querystring');
server.on('request'.function(req, res) {
var postData = ' ';
// Data block received
req.addListener('data'.function(chunk) {
postData += chunk;
});
// Data is received
req.addListener('end'.function() {
postData = qs.parse(postData);
// Cross-domain background Settings
res.writeHead(200, {
'Access-Control-Allow-Credentials': 'true'.// The backend allows sending cookies
'Access-Control-Allow-Origin': 'http://www.domain1.com'.// Allowed domain (protocol + domain name + port)
/* * Set the cookie to domain2 instead of domain1, because the backend cannot write cookies across domains (nginx reverse proxy can do this), * but as long as domain2 write cookie authentication once, All subsequent cross-domain interfaces can obtain cookies from domain2, so that all interfaces can cross-domain access */
'Set-Cookie': 'l=a123456; Path=/; Domain=www.domain2.com; HttpOnly' // HttpOnly prevents js from reading cookies
});
res.write(JSON.stringify(postData));
res.end();
});
});
server.listen('8080');
Copy the code
Reference link: blog.csdn.net/qq_38128179…