What is the Ajax
Ajax, Asynchronous JavaScript and XML, is a technology for creating dynamic web pages that interact with the back end.
Ajax is where scripts independently request data from the server, and when they get the data, they process it and update the web page. In the whole process, the back end is only responsible for providing data, and other things are processed by the front end, realizing the complete business logic of obtaining data → processing data → displaying data.
Synchronous and asynchronous
synchronous
All operations are completed before being returned to the user. In this way, the user waits too long online, giving the user a feeling of being stuck (that is, in the system migration, click the migration, the interface will not move, but the program is still executing, the feeling of being stuck). In this case, the user cannot close the interface; if so, the migration process is interrupted.
asynchronous
Put the user request into a message queue and report back to the user that the migration process has started and you can close the browser. Then the program slowly writes to the database. That’s asynchrony. But the user doesn’t feel stuck and will tell you that your request has been answered. You can close the screen.
The working principle of
An intermediate layer is added between the client (such as the browser) and the server: the Ajax engine. The Ajax engine requests data to the server independently. After the front-end gets the data returned by Ajax, it can use the new data to update the page or carry out other operations, making the user request and server response asynchronous, thus ensuring that the web content can be partially updated without refreshing the page.
<! DOCTYPEhtml>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Ajax</title>
</head>
<body>
<div id="view">
<p>Click the button below to update the data from the Ajax request into the text</p>
</div>
<button type="button" id="btn">Making Ajax requests</button>
<script>
document.getElementById("btn").onclick = ajaxRequest;
function ajaxRequest () {
// Instantiate an XMLHttpRequest object
var xhr = new XMLHttpRequest();
//open() specifies the type of request, THE URL, and whether it is asynchronous
xhr.open("GET"."https://www.w3cschool.cn/statics/demosource/ajax_info.txt".true);
xhr.send();
//send() sends requests, which must be used in conjunction with open
xhr.onreadystatechange = function(){
// Monitor the status of server responses
if (xhr.readyState === 4 && xhr.status === 200) {
// If readyState is 4 and status is 200, the response is successful
document.getElementById("view").innerHTML = xhr.responseText; }}}</script>
</body>
Copy the code
Advantages and Disadvantages
Advantages:
- Page no refresh update, user experience is very good;
- Asynchronous communication, faster response
- Some server work can be transferred to the client, the use of client resources to process, reduce the server and bandwidth pressure, save space and bandwidth rental costs;
- Technology standardization, and by
Wide browser support
, no need to download plug-ins or applets; - Ajax can make Internet applications smaller, faster, and friendlier.
Disadvantages:
- Ajax does not support the browser back button;
- There are security issues where Ajax exposes the details of interactions with the server;
- Not friendly to search engines;
- Broke the exception mechanism of the program;
- Not easy to debug.
The same-origin policy
The composition of the url
A URL address can have the following components: Scheme: //host:post/path? query#fragment
- Scheme: communication protocol, usually HTTP or HTTPS.
- Host: indicates the domain name.
- Post: indicates the port number. This parameter is optional. The default HTTP port number is 80 and HTTPS port number is 443.
- Path: indicates the path. The value is a string separated by a slash (/).
- Query: indicates the query parameter. This parameter is optional.
- Fragment: Information fragment, used to specify a fragment of network resources. This parameter is optional.
Website: https://www.w3cschool.cn:8080/search?w=ajax
https
Is the agreement;www.w3cschool.cn
Is the domain name;8080
Is the port number;/search
Is a path;? w=ajax
Is the parameter of the URL address band;- The lack of
fragment
Information fragment;
What is the same origin policy
The same origin policy is a security protocol and an important security metric in client-side scripts (especially JavaScript). It means that a script can only read the properties of Windows and documents from the same source.
What is homology?
Same-origin indicates that the protocol, domain name, and port in the URL address are the same.
Different paths, same origin
- www.w3cschool.cn
- www.w3cschool.cn/tutorial
- www.w3cschool.cn/minicourse/…
Different protocols, different sources
- www.w3cschool.cn
- www.w3cschool.cn
Different domain names, different sources
- pm.w3cschool.cn
- www.w3cschool.cn
Different ports, different sources
- www.pm.w3cschool.cn
- www.pm.w3cschool.cn:445
Why the same origin policy
When we use Ajax to request back-end data, we can only interact with the same-origin back-end interface. That is, the URL of the back-end interface and the URL of the page that initiates the Ajax request must meet the same-origin policy.
A request from a local server to a remote server that does not meet the same origin policy will cause an error.
For data security. Without the same-origin policy, a hacker can request your backend data on his or her own page, resulting in database content theft and private data leakage.
Cross-domain request
Although Ajax requests need to satisfy the same origin policy, there are scenarios where you really need Ajax access to other “sources” of data (called cross-domain access), and the back-end server needs to set it up accordingly.
If the server supports CORS, you can set access-Control-Allow-Origin to cross-domain. If the browser detects the Settings, Ajax will be allowed to access across domains.
Cross-domain solution:
- The json technology
- Set up the proxy module on the server;
- Modify window.name to achieve cross-domain;
- Use the window.postMessage method introduced in HTML5 to send data across domains;
- , etc…
XMLHttpRequest
At the heart of Ajax technology is the XMLHttpRequest class, or XHR, which allows scripts to make asynchronous calls to HTTP apis. The browser defines the HTTP API on the XMLHttpRequest class, each instance of which represents a separate request/response object, and properties and methods on this instance object allow you to specify details and extract response data.
Create an instance
var xhr = new XMLHttpRequest();
Copy the code
Compatible with
Most browsers support XMLHttpRequest. But versions prior to IE7 (IE5, IE6) do not support the XMLHttpRequest() constructor, which requires an ActiveX object to emulate:
var xhr = new ActiveXObject("Microsoft.XMLHTTP");
Copy the code
Compatible with writing
var xhr = window.XMLHttpRequest ? new window.XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
Copy the code
open()
Once the XMLHttpRequest object is created, the next step in making an HTTP request is to call the open method of the XMLHttpRequest object, specifying the two required parts of the HTTP request: the request method and the URL
xhr.open(method, url, async)
-
Method:
-
The first parameter specifies the HTTP request method, which is case insensitive;
-
Possible values of this parameter include: “GET”, “POST”, “HEAD”, “PUT”, “OPTIONS”, and “DELETE”. “GET” and “POST” are widely supported request methods.
-
-
Url:
-
The second parameter specifies the URL of the HTTP request, which can be absolute or relative.
-
Absolute urls: need to satisfy the same origin policy (unless the server explicitly allows cross-domain requests);
-
Relative URL: that is, the URL relative to the document;
-
-
Async:
-
The third parameter is optional, and a Boolean value can be used to specify whether the script calls the Ajax request asynchronously.
-
The default value of this parameter is true, indicating that the Ajax request is invoked asynchronously without blocking the execution of subsequent scripts.
-
Note:
The open() method can also have the fourth and fifth parameters, the user name and password for HTTP request access authentication, which require configuration on the server and are rarely used.
setRequestHeader
If your HTTP request requires setting the header, the next step after calling the open method is to set it, using the setRequestHeader method
// Set the request header after the open method
xhr.setRequestHeader("Content-Type"."application/x-www-form-urlencoded");
Copy the code
xhr.setRequestHeader(name, value)
- Name: request header name.
- Value: specifies the value of the request header.
send()
The final step in making an HTTP request with XMLHttpRequest is to specify an optional request body and send it to the server using the send method
var xhr = new XMLHttpRequest();
xhr.open("GET"."/statics/demosource/demo_get_json.php");
// Because of the GET request, there is no request body, so we can pass null or omit this parameter when calling send;
xhr.send(null);
Copy the code
var xhr = new XMLHttpRequest();
xhr.open("POST"."/statics/demosource/demo_post_json.php");
// send MSG as the request body
xhr.send(msg);
Copy the code
- POST requests usually have a request body, which can be specified in the SEND method;
- The request body of the POST request,
Should match
setRequestHeader
Method specifies the “Content-type” header.
Get a response
A complete HTTP response consists of a status code, a response header, and a response body, all of which can be retrieved through properties and methods provided by the XMLHttpRequest object.
How do you determine that an HTTP request has returned a response?
In order to be notified when an HTTP response is ready, you must listen for the readyStatechange event on the XMLHttpRequest object. But in order to understand this event type, you need to understand the readyState property, because this event listens for changes in the value of the readyState property.
The readyState property on the XMLHttpRequest object changes from 0 to 4 during the HTTP request
<! DOCTYPEhtml>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Tryrun 2</title>
</head>
<body>
<button id="btn">Let me watch the readyState property change</button>
<script>
var oBtn = document.getElementById("btn");
oBtn.onclick = function () {
// Compatible processing
var xhr = window.XMLHttpRequest ? new window.XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
alert(xhr.readyState);/ / 0
xhr.onreadystatechange = function () {
alert(xhr.readyState);
}
xhr.open("GET"."/statics/demosource/demo_get_json.php");
xhr.send();
}
</script>
</body>
</html>
Copy the code
ReadyState attribute
The readyState property is an integer whose value represents the different HTTP request states.
- 0: initial value, indicating that the request is not initialized.
open
Method has not been called; - 1: start the request. The open method has been called, but the send method has not been called.
- 2: The request is sent. The send method has been invoked, but no response has been received.
- 3: Indicates that the response is received
Part of the response
Data, mainly response headers; - 4: The HTTP response is complete. All response data has been received and can be used on the client.
The readyStatechange event is triggered every time the value of the readyState property changes, but only when the value of the readyState property is 4 is the state we care about because only this state indicates that the HTTP response is ready, We can truly combine the data that the server responds to to achieve our business needs.
Send request specification
<! DOCTYPEhtml>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Tryrun 3</title>
</head>
<body>
<button id="btn">Let me watch the readyState property change</button>
<div id="tip"></div>
<script>
var oBtn = document.getElementById("btn"),
oTip = document.getElementById("tip");
oBtn.onclick = function () {
var xhr = window.XMLHttpRequest ? new window.XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
oTip.innerText = "HTTP response complete"; }}; xhr.open("GET"."/statics/demosource/demo_get_json.php");
xhr.send();
}
</script>
</body>
</html>
Copy the code
Note:
readyState
The value of the attribute only represents the phase of the HTTP request at this time: whether the request was sent or not sent, whether only the response header was received or completed;- “Response completed” only means that the HTTP request is over. As for the server’s response status: whether the request is successful, the request is incorrect, or the server is in error, it needs to pass
The HTTP status code
Judge, it is stored inXMLhttpRequest
thestatus
Attributes;
The status attribute
The status attribute holds the HTTP status code of the server’s response in numeric form, such as the most frequently used “200” indicating that the request was successful and “404” indicating that the URL did not match any resource on the server.
The HTTP status code is a 3-digit code used to represent the response status of the web server. The first digit of all status codes represents one of the five states of the response:
- 1XX: temporary response
- 2 xx: success
- 3xx: redirection
- 4xx: Request error
- 5xx: Server error
What HTTP status codes indicate that we can get HTTP response data?
The status code starting with 2 and 304. The status code starting with 2 indicates that the request is successful, while 304 is a response to the client readable cache, which can also obtain HTTP response data.
<! DOCTYPEhtml>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Tryrun 4</title>
<style>
#btn { margin-top: 7px; }
</style>
</head>
<body>
<div id="tip"></div>
<button id="btn">Click on me to make an Ajax request</button>
<script>
var oBtn = document.getElementById("btn"),
oTip = document.getElementById("tip");
oBtn.onclick = function () {
var xhr = window.XMLHttpRequest ? new window.XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) return;
if (xhr.status >= 200 && xhr.status < 300 || xhr.status === 304) {
oTip.innerText = "HTTP request successful"; }}; xhr.open("GET"."/statics/demosource/demo_get_json.php");
xhr.send();
}
</script>
</body>
</html>
Copy the code
The responseText property
The responseText property stores the body of the response as a string: the server’s response data.
Regardless of the data type returned, the content of the response body is stored in the responseText property;
The response HTML
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if(xhr.readyState ! = =4) return;
if (xhr.status >= 200 && xhr.status < 300 || xhr.status === 304) {
// When the response succeeds, get the response data and assign the data to the localoView.innerHTML = xhr.responseText; }}; xhr.open("GET"."/statics/demosource/demo_get.php");
xhr.send();
Copy the code
In response to json
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if(xhr.readyState ! = =4) return;
if (xhr.status >= 200 && xhr.status < 300 || xhr.status === 304) {
Parse converts the response data to JSON data using json.parse
var res = JSON.parse(xhr.responseText);
// Assign the data attribute in the response data to oTime for contentoTime.innerText = res.data; }}; xhr.open("GET"."/statics/demosource/demo_get_json.php");
xhr.send();
Copy the code
Method of querying HTTP response headers
On the XMLHttpRequest object, the response header information can be queried using the getAllResponseHeaders and getResponseHeader methods.
getAllResponseHeaders
getAllResponseHeaders
Method has no parameters and is used to return all queriable response headers at one time
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if(xhr.readyState ! = =4) return;
if (xhr.status >= 200 && xhr.status < 300 || xhr.status === 304) {
// Get all queryable response headersoView.innerText = xhr.getAllResponseHeaders(); }}; xhr.open("GET"."/statics/demosource/demo_get_json.php");
xhr.send();
Copy the code
getResponseHeader
getResponseHeader
Method for queryingA single
The response header information needs to be passed as a string specifying “header name” :getResponseHeader(headerName)
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if(xhr.readyState ! = =4) return;
if (xhr.status >= 200 && xhr.status < 300 || xhr.status === 304) {
// Query the content-type response header
alert( xhr.getResponseHeader("Content-Type")); }}; xhr.open("GET"."/statics/demosource/demo_get_json.php");
xhr.send();
Copy the code
Note:
Since XMLHttpRequest automatically handles cookies by filtering them out of the set of response headers returned by the getAllResponseHeaders method, And null is returned if “set-cookie” or “set-cookie2” is passed to the getResponseHeader method.
The synchronous response
var xhr = new XMLHttpRequest();
// Specify false as the third argument to the open method
xhr.open("GET"."/statics/demosource/demo_get_json.php".false);
// The call to the send method blocks the execution of subsequent code until the HTTP request completes
xhr.send();
// No longer need to listen for the readyStatechange event
if (xhr.status >= 200 && xhr.status < 300 || xhr.status === 304) {
oTime.innerText = JSON.parse(xhr.response).date;
} else {
// If the request is unsuccessful, an error is reported
throw new Error(xhr.status);
}
Copy the code
Abort the request
If the HTTP request takes longer than expected, you can call the ABORT method on the XMLHttpRequest object to abort the HTTP request.
var xhr = new XMLHttpRequest();
var timer = null; // Used to store timer id
xhr.onreadystatechange = function () {
if(xhr.readyState ! = =4) return;
if (xhr.status >= 200 && xhr.status < 300 || xhr.status === 304) {
clearTimeout(timer); // Cancel the timer if it does not time out}}; xhr.open("GET"."/statics/demosource/demo_get_json.php");
xhr.send();
Abort the GET request after 2 seconds
timer = setTimeout(function(){
xhr.abort();
}, 2000)
Copy the code