A, Ajax
It is a set of methods provided by the browser, which can realize the page without refreshing the data and improve the user’s browsing experience of the website application.
1. Application scenarios
- More data is pulled and loaded on the page
- There is no refresh page for list data
- The form leaves the focus data validation
- Search box prompts text drop – down list
2. Operation principle
Ajax acts as a proxy for the browser to send requests and receive responses to improve the user experience by partially updating the page data without affecting the user’s ability to browse the page.
3. Implementation steps
3.1 Creating Ajax objects
var xhr = new XMLHttpRequest();
Copy the code
3.2 Tell Ajax the address and method of the request
xhr.open('get'.'http://www.example.com');
Copy the code
3.3 Sending a Request
xhr.send();
Copy the code
3.4 Obtaining the response data from the server to the client
xhr.onload = function () {
console.log(xhr.responseText);
}
Copy the code
4. Request parameters
4.1 GET Request Mode
xhr.open('get'.'http://www.example.com?name=zhangsan&age=20');
Copy the code
4.2 POST Request Mode
xhr.setRequestHeader('Content-Type'.'application/x-www-form-urlencoded');
xhr.send('name=zhangsan&age=20');
Copy the code
In the process of HTTP request and response, both request parameters and response contents, if they are object types, will eventually be converted into object strings for transmission.
JSON.parse() // Convert json strings to JSON objects
JSON.stringify() // Convert a JSON object to a JSON string
Copy the code
5. Request packets
The blocks of data that are passed during HTTP requests and responses are called messages. They contain the data to be transmitted and additional information in a specified format.
6. Format of request parameters
6.1 application/x – WWW – form – urlencoded
name=zhangsan&age=20& sex = maleCopy the code
6.2 application/json
{name: 'zhangsan'.age: '20'.sex: 'male'}
Copy the code
Specifying the content-Type attribute as application/ JSON in the request header tells the server that the current request parameter is in JSON format.
Note: GET requests cannot submit JSON object data format, and traditional web site form submission does not support JSON object data format.
7. Obtain the response from the server
7.1 Ajax status code
Each step in the process of creating an Ajax object, configuring an Ajax object, sending the request, and receiving the server-side response data corresponds to a value called the Ajax status code.
0: the request is not initialized (open() has not been called) 1: the request has been established but not sent (send() has not been called) 2: the request has been sent 3: the request is being processed and usually some data is available in the response 4: the response has been completed and the server’s response is ready to be retrieved and used
xhr.readyState // Get the Ajax status code
Copy the code
7.2 the onreadystatechange event
This event is automatically triggered when the Ajax status code changes.
The Ajax status code can be retrieved and judged in the event handler, and when the status code is 4, the server response data can be retrieved via xhr.responseText.
// When the Ajax status code changes
xhr.onreadystatechange = function () {
// Determine when the Ajax status code is 4
if (xhr.readyState == 4) {
// Get the response data from the server
console.log(xhr.responseText); }}Copy the code
7.3 Differences between the Two Methods for Obtaining server Responses
The difference between describing | The onload event | The onreadystatechange event |
---|---|---|
Whether it is compatible with earlier VERSIONS of IE | Are not compatible | Compatible with |
Whether you need to determine the Ajax status code | Don’t need | Need to be |
Number of calls | At a time | Many times |
Ajax error handling
8.1 xhr.status Obtaining the HTTP status code
You can judge the status code returned by the server and process it separately.
8.2 The network is interrupted and requests cannot be sent to the server.
The onError event below the XHR object is raised, and the error is handled in the onError event handler.
8.3 Common HTTP Status Codes
- 1XX The server receives a request
- The request for 2xx is successful, for example, 200
- 3xx redirection, such as 302
- 301 Permanent redirection (with location, the browser handles it automatically)
- 302 Temporary Redirection (with Location, handled automatically by the browser)
- 304 The resource has not been modified (the resource has been requested and has not expired)
- 4XX client error, such as 404
- 403 has no permissions. The server doesn’t want you to access it
- 404 resource not found
- 5XX server error, such as 500
-
500 Server error
-
504 Gateway timeout means that the server acting as a gateway or proxy does not receive the request from the upstream server in time
-
9. The Cache of Internet Explorer of earlier versions is faulty
In earlier versions of Internet Explorer, Ajax requests have a serious caching problem, meaning that only the first request is actually sent to the server without changing the address of the request, and subsequent requests are retrieved from the browser’s cache. Even if the data on the server is updated, the client still gets the old data in the cache.
Request parameters are appended to the request address to ensure that the value of the request parameters is not the same in each request.
xhr.open('get'.'http://www.example.com?t=' + Math.random());
Copy the code
10. Ajax encapsulation
Ajax sends too much code for one request, and redundant and repetitive code for multiple requests. We wrap the request code in a function that is called when the request is made.
Questions to consider for request parameters
- Request parameter location problem
- Get requests are placed after the request address
- Post is placed in the SEND method
- Request parameter format problem
- application/x-www-form-urlencoded
- application/json
// The attribute name of the object can describe the attribute
ajax({
// Request type
type: 'post'.// Request an address
url: 'http://localhost:3000/json'.// Request parameters
data: {
username: 'zhangsan'.id: '12345'
},
// Request format
header: {
'Content-Type': 'application/json'
},
The callback function was successfully executed
success: function(data, xhr) {
console.log('Here is the success function');
console.log(data); }});Copy the code
// Encapsulate ajax functions
function ajax(options) {
// Stores default values
var defaults = {
type: 'get'.url: ' '.data: {},
header: {
'Content-Type': 'application/x-www-form-urlencoded'
},
success: function() {},
error: function() {}};Object.assign(defaults, options);
// Create ajax objects
var xhr = new XMLHttpRequest();
// Concatenate the variables of the request parameters
var params = ' ';
// Loop over the object format parameters passed in by the user
for (var attr in defaults.data) {
// Convert arguments to string format
params += attr + '=' + defaults.data[attr] + '&';
}
// Intercepts the & at the end of the string
params = params.substr(0, params.length - 1);
// Determine the request type
if (defaults.type == 'get') {
defaults.url = defaults.url + '? ' + params;
}
// Configure the Ajax object
xhr.open(defaults.type, defaults.url);
// If the request is POST
if (defaults.type == 'post') {
var contentType = defaults.header['Content-Type'];
// Sets the type of request parameter format
xhr.setRequestHeader('Content-Type', contentType);
if (contentType == 'application/json') {
// Pass json data format parameters to the server
// The argument must be a pass string
xhr.send(JSON.stringify(defaults.data));
} else {
// Pass the normal type of request parameters to the serverxhr.send(params); }}else {
// Send the request
xhr.send();
}
// Listen for the onload event on the XHR object
Emitted when the XHR object has received the response data
xhr.onload = function() {
// xhr.getResponseHeader();
// Get the data in the response header
var contentType = xhr.getResponseHeader('Content-Type');
// The server returns data
var responseText = xhr.responseText;
// If the response type contains application/json
if (contentType.includes('application/json')) {
// Convert json strings to JSON objects
responseText = JSON.parse(responseText);
}
// When the HTTP status code is 200
if (xhr.status == 200) {
// If the request is successful, call the function that handles the success
defaults.success(responseText, xhr);
} else {
// If the request fails, call the function that handles the failuredefaults.error(responseText, xhr); }}}Copy the code
11. Same-origin policy
11.1 Restrictions on Ajax Requests
Ajax can only send requests to its own server. For example, if there is A website A and A website B, the HTML files in website A can only send Ajax requests to the server of website A, and the HTML files in website B can only send Ajax requests to website B, but website A cannot send Ajax requests to website B. Similarly, Web site B also cannot send Ajax requests to Web site A.
11.2 What is homology
If two pages have the same protocol, domain name, and port, they belong to the same source. If one of them is different, it is a different source
Protocol:// Domain name: port
Copy the code
www.example.com/dir/page.ht… | Whether the same | why |
---|---|---|
www.example.com/dir2/other…. | homologous | |
Example.com/dir/other.h… | Different source | Domain name is different |
V2.www.example.com/dir/other.h… | Different source | Domain name is different |
www.example.com:81/dir/other.h… | Different source | Different ports |
www.example.com/dir/page.ht… | Different source | Different source |
11.3 Purpose of the same-origin policy
The same-origin policy ensures user information security and prevents malicious websites from stealing data. The original same-origin policy refers to the Cookie set by website A on the client, and website B cannot be accessed.
With the development of the Internet, the same origin policy is becoming more and more strict. In the case of different sources, one of the stipulations is that Ajax requests cannot be sent to non-same origin addresses. If a request is made, the browser will report an error.
11.4 Solution of the Same Origin Policy
- JSONP
- CORS cross-domain resource sharing
- Server agent
1. Use JSONP to solve the homology restriction problem
Ajax does not cross domains, but img SRC (get image), link href (get CSS), and script SRC (get javascript) do not comply with the same origin policy and can cross domains. JSONP, introduced here, uses script SRC to retrieve data across domains.
JSONP, which stands for JSON with Padding, is not an Ajax request, but it can simulate an Ajax request.
- Write the server-side request addresses of different sources in the SRC attribute of the script tag
<script src="www.example.com"></script>/
Copy the code
- The server-side response data must be a function call, and the actual data to be sent to the client needs to be the parameter of the function call.
const data = 'fn({name: "张三", age: "20"})';
res.send(data);
Copy the code
- Define the function fn under the client global scope
function fn (data) {}Copy the code
- The data returned by the server is processed inside the FN function
function fn (data) { console.log(data); }
Copy the code
JSONP code optimization
- The client needs to pass the function name to the server.
- Turn the sending of script requests into dynamic requests.
- Encapsulate jSONP functions to facilitate request sending.
- Res.jsonp method for server-side code optimization.
<script src="http://localhost:3000/province? jsonp=jsonp"></script>
Copy the code
2. CORS cross-domain resource sharing
CORS: Cross-Origin Resource Sharing, or Cross-domain resource sharing, allows browsers to send Ajax requests to cross-domain servers, overcoming the limitation that Ajax can only be used in the same source.
origin: http://localhost:3000
Copy the code
Access-Control-Allow-Origin: 'http://localhost:3000'
Access-Control-Allow-Origin: The '*'
Copy the code
Node server set the response header example code:
// Intercept all requests
app.use((req, res, next) = > {
1. Allow those clients to access me
// * allows all clients to access me
// res.header('Access-Control-Allow-Origin', 'http://localhost:3000');
res.header('Access-Control-Allow-Origin'.The '*');
// 2. Which request methods are allowed for clients to access me
res.header('Access-Control-Allow-Methods'.'get,post');
next();
});
Copy the code
3. Server-side solution for accessing non-same-source data
The same origin policy is a limitation imposed by the browser on Ajax technology; there is no such restriction on the server side
const request = require('request');
app.get('/server'.(req, res) = > {
// Want to access data from a non-source server
request('http://localhost:3001/cross'.(err, response, body) = > {
res.send(body);
});
});
Copy the code
11.5 withCredentials attribute
When sending a cross-domain request using Ajax technology, cookie information is not carried in the request by default.
WithCredentials: specifies whether to carry cookie information when cross-domain requests are involved. The default value is false access-Control-allow-credentials: true Allows clients to send requests with cookies
xhr.withCredentials = true;
Copy the code
// Server Settings
app.use((req, res, next) = > {
1. Allow those clients to access me
// * allows all clients to access me
// Note: If the value cannot be * in the cross-domain request, pass the specific domain name information
res.header("Access-Control-Allow-Origin"."http://localhost:3000");
// 2. Which request methods are allowed for clients to access me
res.header("Access-Control-Allow-Methods"."get,post");
// 3. Allow clients to send cross-domain requests with cookie information
res.header("Access-Control-Allow-Credentials".true);
next();
});
Copy the code
Second, the FormData
1. Function of the FormData object
-
Emulating an HTML form is equivalent to mapping an HTML form to a form object and automatically stitching the data in the form object into the format of the request parameters.
-
Asynchronously upload binary files
2. Use
- Preparing HTML forms
<form id="form">
<input type="text" name="username" />
<input type="password" name="password" />
<input type="button"/>
</form>
Copy the code
- Convert the HTML form to a formData object
var form = document.getElementById('form');
var formData = new FormData(form);
Copy the code
- Submit form object
xhr.send(formData);
Copy the code
Note:
-
A Formdata object cannot be used for A GET request because the object needs to be passed to the SEND method, and the parameters of a GET request can only be placed after the request address.
-
The bodyParser module on the server side cannot parse the formData object formData, so we need to use the formidable module to parse it.
3. Instance methods of the FormData object
- Gets the value of an attribute in the form object
// Get key as the first value of key
formData.get('key');
// Get all values of key, return values of array type
formData.getAll('key');
Copy the code
- Sets the value of an attribute in the form object
formData.set('key'.'value');
Copy the code
- Deletes the value of an attribute in the form object
formData.delete('key');
Copy the code
- Appends attribute values to the form object
formData.append('key'.'value');
Copy the code
Note: The difference between the set method and the Append method is that in the case of an existing attribute name, the set method overrides the value of the existing key name, and Append retains both values.
4. Upload the FormData binary file
<input type="file" id="file"/>
Copy the code
var file = document.getElementById('file')
// When the user selects a file
file.onchange = function () {
// Create an empty form object
var formData = new FormData();
// Appends the user-selected binary file to the form object
formData.append('attrName'.this.files[0]);
// Configure the Ajax object. The request must be POST
xhr.open('post'.'www.example.com');
xhr.send(formData);
}
Copy the code
5. Display the FormData file upload progress
// When the user selects a file
file.onchange = function () {
// The onProgress event continues to be emitted during file upload
xhr.upload.onprogress = function (ev) {
// Current uploaded file size/total file size converts the result to a percentage
// Assign the result to the width property of the progress bar
bar.style.width = (ev.loaded / ev.total) * 100 + The '%'; }}Copy the code
6. FormData file upload image instant preview
After we upload the image to the server, the server usually passes the image address to the client as response data. The client can retrieve the image address from the response data and display the image on the page.
xhr.onload = function () {
var result = JSON.parse(xhr.responseText);
var img = document.createElement('img');
img.src = result.src;
img.onload = function () {
document.body.appendChild(this); }}Copy the code
Ajax in jQuery
1. $. Ajax () method
1.1 Sending Ajax Requests
$.ajax({
type: 'get'.url: 'http://www.example.com'.data: { name: 'zhangsan'.age: '20' },
contentType: 'application/x-www-form-urlencoded'.beforeSend: function () {
return false
},
success: function (response) {},
error: function (xhr) {}});Copy the code
1.2 Sending a JSONP Request.
$.ajax({
url: 'http://www.example.com'.// Specify the current jSONP request to be sent
dataType: 'jsonp'.// Modify the name of the callback argument
jsonp: 'cb'.// Specify the function name
jsonCallback: 'fnName'.success: function (response) {}})Copy the code
2. Serialize method
Serialize () serializes form elements into strings.
SerializeArray () serializes the form elements as JSON data.
$.get(), $.post()
The.get method is used to send get requests, the.get method is used to send GET requests, the.get method is used to send GET requests, and the.POST method is used to send POST requests.
$.get('/base'.'name=zhangsan&age=30'.function(response) {});
Copy the code
$.post('http://www.example.com', {name: 'lisi'.age: 22}, function (response) {})
Copy the code
Global events
Whenever an Ajax request is sent on the page, the corresponding global event is fired
.ajaxStart() // Triggered when the request starts to be sent
.ajaxComplete() // Triggered when the request completes
Copy the code
NProgress: Nanoscale progress bar, using realistic trickle-flow painting to tell the user what is happening!
<link rel='stylesheet' href='nprogress.css'/>
<script src='nprogress.js'></script>
Copy the code
NProgress.start(); // The progress bar starts moving
NProgress.done(); // The progress bar finishes moving
Copy the code
// Triggered when an Ajax request is sent in the page
$(document).on('ajaxStart'.function() {
NProgress.start();
})
// Triggered when the page request completes
$(document).on('ajaxComplete'.function() {
NProgress.done();
});
Copy the code
RESTful apis
A new API design approach (already widely used)
Traditional API design: Treat each URL as a function
Restful API design: Treat each URL as a unique resource
1. Comparison between traditional methods and current methods
methods | The methods of traditional | Now, the methods of |
---|---|---|
get | Get data from the server | To get the data |
post | Submit data to the server | Increase the data |
patch / put | Update the data | |
delete | Delete the data |
2. How to design as a resource?
2.1 Try not to use URL parameters
- Traditional API design: / API /list? pageIndex = 2
- Restfux API: /api/list/2
2.2 Using Method to represent operation types Traditional API design
- Post request/API/create – blog
- Post request/API/update – blog? id=100
- Get request/API/get – blog? id=100
Restfux API design
- Post request/API/blog
- Patch request/API/blog / 100
- Get request/API/blog / 100
Fifth, the Fetch
MDN Fetch
The Fetch API is a new Ajax solution where Fetch returns promises. Fetch is not a further encapsulation of Ajax, but rather native JS, without using XMLHttpRequest objects
Fetch (url, options).then()
Disadvantages:
- You need to configure the content-Type of the Header for sending network requests. Cookies are not carried by default
- Error handling is cumbersome (only network errors reject, HTTP status codes 404 or 500 are not marked as reject)
- There is no support for canceling a request, viewing the progress of a request, and so on
1. Basic usage of FetchAPI
1.1 the get
fetch('http://localhost:3000/books? id=123', {
// GET requests can be omitted without writing the default is GET
method: 'get'
}).then(function(data) {
// Part of the text() method data fetchAPI, which returns a Promise instance object to fetch the data returned in the background
return data.text();
}).then(function(data) {
// In this then we can get the final data
console.log(data)
});
Copy the code
1.2 the delete
fetch('http://localhost:3000/books/789', {
method: 'delete'
})
Copy the code
1.3 post
fetch('http://localhost:3000/books', {
method: 'post'.body: 'uname=list&pwd=123'.// Configure the request header
headers: {
'Content-Type': 'application/x-www-form-urlencoded'}})Copy the code
1.4 put
fetch('http://localhost:3000/books/456', {
method: 'put'.body: JSON.stringify({
uname: 'Joe'.pwd: '123'
}),
// Configure the request header
headers: {
'Content-Type': 'application/json'}})Copy the code
2. Response format
.text() converts the retrieved data to a string that returns a Promise instance object. Json () converts the retrieved data to a JSON transform object that returns a Promise instance object