1, jQuery mode
The usage of XMLHttpRequest provided in the browser is complex, so jQuery encapsulates XMLHttpRequest and provides a series of Ajax related functions, which greatly reduces the difficulty of using Ajax.
The three most common methods for initiating Ajax requests in jQuery are as follows:
- $. get() get data
$.get(url,[data],[callback])
Parameter name parameter type required description
url string is the address of the resource to be requested
data object no parameter to be carried during resource request
Callback function no is the callback function when the request is successful
① $. get() initiates a request without parameters
$.get('http://www.atguigu.com:3006/a...',function(res){
console.log(res) / / res here is the data returned by the server
})
② $. get() initiates a request with parameters
$.get('http://www.atguigu.com:3006/a...', { id: 1 }, function(res){
console.log(res)
})
Remember!!! Where parameters are in the form of objects
- $. post() submit data
$.post(url,[data],[callback])
Parameter name parameter type required description
url string is the address to submit data
Data objectno data to submit
Callback function no is the callback function when the data is submitted successfully
$. post() submits data to the server
$.post(
'http://www.www.atguigu.com:30... ', // Requested URL address
{bookname: 'outlaws of the marsh', author: 'Shi Naian', publisher: 'Shanghai book publishing house'}, / / data submitted
function(res) { // Callback function
console.log(res)
}
)
- $. ajax() can get or submit data
$.ajax({
type: ' ', // The method of the request, such as GET or POST
url: ' ', // Requested URL address
Data: {}, / / the data to be carried in this request
success: function(res) { } // Callback function after successful request
})
① Use $. ajax() to initiate a GET request (just set the type attribute to 'GET')
$.ajax({
type: 'get',
url: 'http://www.www.atguigu.com:30...',
data: { id: 1 }
success: function(res) {
console.log(res)
}
})
② POST requests are initiated using $. ajax()
$.ajax({
type: 'post',
url: 'http://www.atguigu.com:3006/a...',
data: {
bookname: 'outlaws of the marsh',
author: 'Shi Naian',
publisher: 'Shanghai book publishing house'
},
success: function(res) {
console.log(res)
}
})
Now that we understand the concept, let's practice it. Here's an example: realize the addition, deletion and display function of book list
The implementation code is as follows:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <link rel="stylesheet" href="bootstrap.css"> <script src="jQuery.min.js"></script>
</head>
<body style="padding: 15px">
<div class="panel panel-primary"> <div class="panel-heading"> <h3 class="panel-title">Add new book</h3> </div> <div class="panel-body form-inline"> <div class="input-group"> <div class="input-group-addon">title</div> <input type="text" class="form-control" id="iptBookname" placeholder="Please enter the title of the book"> </div> <div class="input-group"> <div class="input-group-addon">author</div> <input type="text" class="form-control" id="iptAuthor" placeholder="Please enter author"> </div> <div class="input-group"> <div class="input-group-addon">press</div> <input type="text" class="form-control" id="iptPublisher" placeholder="Please enter the publishing house"> </div> <button id="btn" class="btn btn-primary">add to</button> </div> </div> <table class="table table-bordered table-hover"> <thead> <tr> <th>Id</th> <th>title</th> <th>author</th> <th>press</th> <th>operation</th> </tr> </thead> <tbody id="tb"> </tbody> </table> <script> $(function(){ //Get book list data function getBookList(){ $.get('http://www.liulongbin.top:3006/api/getbooks',function(res){ if(res.status !== 200) return alert('Failed to get data!'); // Store the obtained data in the array var rows = [] $.each(res.data, function(i,item){ rows.push('<tr><td>'+item.id+'</td><td>'+item.bookname+'</td><td>'+item.author+'</td><td>'+item.publisher+'</td><td><a href:"javascript:;" class="del" data-id="'+item.id+'">delete</a></td></tr>') }) // Convert array to string and render to page $('#tb').empty().append(rows.join('')) }) } getBookList() //Delete book $('tbody').on('click','.del',function(){ var id = $(this).attr('data-id') $.get('http://www.liulongbin.top:3006/api/delbook',{id: id},function(res){ if(res.status !== 200) return alert('Failed to delete book!') // Call this function to render the page again getBookList() }) }) $('#btn').on('click',function(){ // The trim() function removes spaces at both ends of a string var bookname = $('#iptBookname').val().trim() var author = $('#iptAuthor').val().trim() var publisher = $('#iptPublisher').val().trim() if(bookname.length <= 0 || author.length <=0 || publisher.length <=0) { return alert('Please fill in the complete book information!') } // Add books $.post('http://www.liulongbin.top:3006/api/addbook',{bookname: bookname, author: author,publisher: publisher},function(res){ if(res.status !== 201) return alert('Failed to add book!') getBookList() // Clear the contents of the input box $('#iptBookname').val('') $('#iptAuthor').val('') $('#iptPublisher').val('') }) }) }) </script>
</body>
</html>
2, xhr mode
XMLHttpRequest (xhr) is a Javascript object provided by the browser. Through it, you can request data resources on the server Front end training The Ajax functions in jQuery are encapsulated based on xhr objects
- Use xhr to initiate GET requests
The method is shown in the figure below:
// 1. Create xhr object
var xhr = new XMLHttpRequest()
// 2. Call the open function to specify the request method and URL address
xhr.open('GET','http://www.atguigu.com:3006/a...')
// 3. Call the send function to initiate an Ajax request
xhr.send()
// 4. Listen to onreadystatechange event
xhr.onreadystatechange = function() {
// 4.1 listen for the request status readyState of the xhr object and the status of the server response
if(xhr.readyState === 4 && xhr.status === 200) {
// 4.2 print the data returned by the server
console.log(xhr.responseText);
}
}
If a GET request with parameters is initiated, you only need to specify the parameters for the URL address during the call to xhr.open:
xhr.open('GET','http://www.liulongbin.top:300... Journey to the West ')
Multiple parameters are connected by &
- Use xhr to initiate a POST request
The method is shown in the figure below:
// 1. Create xhr object
var xhr = new XMLHttpRequest()
// 2. Call the open function to specify the request method and URL address
xhr.open('POST','http://www.liulongbin.top:300...')
// 3. Set content type attribute (fixed writing method)
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded')
// 4. Call the send function and submit the data to the server in the form of query string
xhr.send('bookname = outlaws of the marsh & author = Shi Naian & Publisher = Tianjin book publishing house ')
// 5. Listen to onreadystatechange event
xhr.onreadystatechange = function() {
// 4.1 listen for the request status readyState of the xhr object and the status of the server response
if(xhr.readyState === 4 && xhr.status === 200) {
// 4.2 print the data returned by the server
console.log(xhr.responseText);
}
}
The difference between sending PSOT and GET requests in xhr mode:
① The location of passing data parameters is different: the GET method is written after the URL address, while the POST method is written in xhr.send()
② When initiating a POST request, you must write xhr.setrequestheader ('content type ',' application / x-www-form-urlencoded '), and the GET request does not need to write
3, axios mode
axios is a library that focuses on network data requests. Compared with the native XMLHttpRequest object, axios is simple and easy to use Compared with jQuery, axios is lighter and only focuses on network data requests
Import the axios.js package before use
- Using axios to initiate GET requests
Syntax:
Axios. Get ('url ', {params: {/ parameter /}}). then(callback)
The code is as follows:
// Request URL address
var url = 'http://www.liulongbin.top:300...'
// Requested parameter object
var paramsObj = { name: 'zs', age: 20 }
// Call axios.get() to initiate a GET request
axios.get(url, { params: paramsObj }).then(function(res){
// res.data is the data returned by the server
var result = res.data
console.log(res);
})
- Using axios to initiate POST requests
Syntax:
axios.post('url', {/ parameter /}). then(callback)
The code is as follows:
// Request URL address
var url = 'http://www.liulongbin.top:300...'
// Data to be submitted to the server
Var dataobj = {location: 'Beijing', address: 'Shunyi'}
// Call axios.post() to initiate a POST request
axios.post(url, dataObj).then(function(res){
// res.data is the data returned by the server
var result = res.data
console.log(res);
})
Differences between GET and POST syntax initiated by axios:
When making a GET request, the parameters should be provided through the params attribute instead of POST
- Request directly using axios
axios also provides functions similar to $. ajax() in jQuery. The syntax is as follows:
axios({
method: 'request type',
URL: 'requested URL address'
Data: {/ post data /},
Params: {/ get parameter /}
}).then(callback)
① Directly use axios to initiate GET requests
axios({
method: 'GET',
url: 'http://www.liulongbin.top:300...',
params: { // The GET parameter is provided through the params attribute
name: 'zs',
age: 20
}
}).then(function(res){
console.log(res.data);
})
② POST requests are initiated directly using axios
axios({
method: 'POST',
url: 'http://www.liulongbin.top:300...',
data: { // The POST parameter should be provided through the data attribute
bookname: 'self cultivation of programmers',
price: 666
}
}).then(function(res){
console.log(res.data);
})
Case practice: use axios to initiate GET and POST requests to obtain data and render it to the page
Implementation code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <script src="./axios.js"></script> <style> body { padding-left: 50px; } .container { width: 300px; height: 150px; box-shadow: 0 0 5px rgba(0,0,0,0.8); background-color: #c7c7c7; margin-bottom: 20px; } </style>
</head>
<body>
<div class="container"> </div> <button id="btn1">get replace</button> <button id="btn2">post replace</button> <script> document.querySelector('#btn1').addEventListener('click',function(){ var url = 'https://xl.xilinglaoshi.com:8001/fenshou' axios({ method: 'GET', url: url, }).then(function(res){ // Get the required data and render it to the page document.querySelector('.container').innerHTML = res.data.data[0].content; }) }) document.querySelector('#btn2').addEventListener('click',function(){ var url = 'https://xl.xilinglaoshi.com:8001/qingshi' axios({ method:'POST', url: url, }).then(function(res){ document.querySelector('.container').innerHTML = res.data.data[0].content; }) }) </script>
</body>
</html>