request
www.w3school.com.cn/jquery/jque…
$.ajax()
Common options:
• URL: request address
• Type: request method, default is GET
• dataType: server response dataType
• contentType: request body contentType, default application/x-www-form-urlencoded
• Data: Data that needs to be passed to the server, via the URL if GET or the request body if POST
• timeout: specifies the request timeout period
• beforeSend: Triggered before the request is initiated
• Success: Triggered after the request is successful (response status code 200)
• Error: The request fails
• Complete: Request completion triggers (successful or not)
A GET request
$.get()
• GET request shortcuts
• $. Get (url, data, the callback)
// Send a get request
$.ajax({
url: "http://localhost:3000/comments".type: "get".dataType: "json".data: {"id": 2},
success: function (data) {
console.log(data); }})// The simplified method sends the GET request directly
$.get("http://localhost:3000/comments", {"id": 1}, function (data) {
console.log(data);
})
Copy the code
A POST request
$.post()
• Shortcuts to POST requests
• $. Post (url, data, the callback)
POST is equivalent to adding a piece of data and returns the newly added data
// Send a POST request
$.ajax({
url: "http://localhost:3000/comments".type: "post".dataType: "json".data: {"postId": 2."content": "bad"},
success: function (data) {
console.log(data); }})// $.post() shortcut to send a request
$.post("http://localhost:3000/comments", {"postId": 3."content": "bad"},function (data) {
console.log(data);
})
Copy the code
Before and after results of shortcut methods:
Put the change
There is no quick fix
- The URL has changed, for example, to change the data with ID 4 in comments, add
/ 4
- It can be changed locally or as a whole, and the changed data is
data
If an attribute is missing, there is no corresponding attribute in the changed data.
// put requests to change data
$.ajax({
url: "http://localhost:3000/comments/4".type: "put".dataType: "json".data: {"content": "good"."postId": 2},
success: function (data) {
console.log(data)
}
})
Copy the code
Delete delete
- No return, no need to pass in, no need to write
data
anddataType
// Delete request to delete data
$.ajax({
url: "http://localhost:3000/comments/5".type: "delete".success: function (data) {
console.log(data)
}
})
Copy the code
AjaxSetup () method
By setting the default parameters, you don’t have to write the same stuff in other Ajax () methods, simplifying things.
// the ajaxSetup() method sets the default parameters
$.ajaxSetup({
url: "http://localhost:3000/users".type: "post"
})
// Send an Ajax request
$.ajax({
data: {"name": "polly"."age": 17."class": 4}
})
$.ajax({
data: {"name": "james"."age": 18."class": 4}})Copy the code
Axios
Axios is the most widely used AJAX wrapper library at unpkg.com/axios/dist/…
Import using the script tag
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
Copy the code
Example: Get request
axios.get("http://localhost:3000/users? id=1")
.then(function (response) {
console.log(response.data)
})
.catch(function (error) {
console.log(error)
})
Copy the code
The content of response:
Response. data gets the data we need
Axios API
Requests can be created by passing the configuration to Axios () in one of two ways:
-
Axios (config), config is the configuration option for the object format
-
Axios (url, config) config can be set without default get. It’s no different than the first method, except that you put the URL out front.
// axios(url, config) method
axios("http://localhost:3000/posts", {
params: {
id: 1
}
})
.then(function (res) {
console.log(res.data)
})
.catch(function (error) {
console.log(error)
})
Copy the code
Common configuration items:
• URL Specifies the server URL used for the request, required
• Method Specifies the method used to create a request, such as GET and POST
• baseURL passes the relative URL prefix, which is automatically added to the URL without setting
• Headers Is a custom request header to be sent. The value is an object type parameter set to POST (can be omitted, default is JSON).
• The URL parameter that params will send with the request, whose value is an object type parameter, set to the GET or DELETE methods. It is also possible to write in the URL without setting params.
• Data The data that is sent as the request body
• timeout Specifies the number of milliseconds in which the request will timeout (0 indicates no timeout)
• responseType Indicates the data type of the server response. The default value is JSON and you do not need to set this parameter
• Axios (URL, config) config Optional
“Then” and “catch”
axios()
.then(function (response) {
// The response information object of a normal request is Response
})
.catch(function (error) {
// Catch an error
})
Copy the code
Global configuration default value
You can specify configuration defaults that will be used on individual requests
case
// Global configuration defaults
axios.defaults.baseURL = "http://localhost:3000";
/ / axios method
axios({
url: "/comments".method: "get"
}).then(function (res) {
console.log(res.data)
}).catch(function (error) {
console.log(error)
})
Copy the code
The interceptor
Intercepts requests or responses before they are processed by THEN or catch.
Global interception, which intercepts all AXIos methods, replaces the global configuration default.
Request interceptor: Sets the contents of the Request interceptor to the AXIos method before the THEN and catch execution of the AXIos method.
Response interceptor: Gets the response content before the THEN and catch methods and returns it to the AXIos method for execution. For example, you can return only the data part in response, but you can not add.data in then
// Use the interceptor to intercept the request
axios.interceptors.request.use(function (config) {
config.params = {
id: 2
}
config.baseURL = "http://localhost:3000"
return config
})
// Intercepts the response
axios.interceptors.response.use(function (response) {
return response.data;
})
/ / axios method
axios("/posts")
.then(function (res) {
console.log(res)
})
.catch(function (error) {
console.log(error)
});
Copy the code
Quick request method
• axios. Get ([url, config])
• axios. Post ([url, data [, config]])
• axios. Delete ([url, config])
• axios. Put ([url, data [, config]])
Get is the same as DELETE, post is the same as PUT
axios.get(url[, config])
/ / get request
// Add the parameters directly to the URL
axios.get("http://localhost:3000/users? id=2")
.then(function (res) {
console.log(res.data)
})
// Method 2: Pass the parameter through params
axios.get("http://localhost:3000/users", {params: {
id: 3
}
})
.then(function (res) {
console.log(res.data)
})
Copy the code
axios.post(url[, data[, config]])
// Post request to add data
axios.post("http://localhost:3000/users", {"name": "nancy"."age": 19."class": 2
})
.then(function (res) {
console.log(res.data)
})
Copy the code
Post’s then() method doesn’t need to be written because it’s essentially adding data; But get must write the then() method, because subsequent operations are performed on the data.
XMLHttpRequest 2.0
onload / onprogress
• Xhr.onload event: fires only when the request completes (when readyState=4), replacing the previous native Ajax end-of-response condition.
• Xhr. onProgress event: emitted only while the request is in progress (when readyState=3), not often
var xhr = new XMLHttpRequest();
xhr.open("GET"."http://localhost:3000/posts");
// Write before send for synchronous asynchrony
xhr.onload = function () {
console.log("load".this.readyState)
}
xhr.onprogress = function (e) {
console.log("progress".this.readyState)
// The number of data received during a periodic request
console.log(e.loaded);
// Total number of received data
console.log(e.total);
}
xhr.send(null);
Copy the code
The response properties
The response body is expressed as an object whose type depends on the value of responseType. Set the responseType value to request data of a specific type, avoiding the need to parse() later to convert the data to an object.
ResponseType is set only after the call to open() initializes the request and before the call to send() sends the request to the server.
var xhr = new XMLHttpRequest();
xhr.open("GET"."http://localhost:3000/posts");
xhr.responseType = "json";
xhr.onload = function () {
console.log(this.response);
}
xhr.send(null);
Copy the code