Encapsulate Ajax functions

1. The effect to be achieved

itheima({
      method: 'Request type',
      url: 'Request address',
      data: {
       // 'Request parameter object'
      },
      success: function (res) {  // Successful callback function
        console.log(res)  // Print data
      }
})

2. Define options parameter options

The itheima() function is our custom Ajax function. It receives a configuration object as a parameter. The following attributes can be configured in the configuration object.

  • method request type
  • url The requested URL address
  • data The data carried by the request
  • success The callback function after the request is successful

3. Processing data parameters

The data object needs to be converted into the query string format and submitted to the server, so the resolveData function is defined in advance as follows.

/*** Process the data parameter
* @param {data} Data that needs to be sent to the server
* @returns {string} Return the spliced query string name=zs&age=10
*/
function resolveData(data) {
  var arr = []
  for (var k in data) {
    var str = k + '=' + data[k]
    arr.push(str)
  }

  return arr.join('&')
}

4. Define the itheima function

In the itheima() function, you need to create an xhr object and listen for the onreadystatechange event.

function itheima(options) {
  var xhr = new XMLHttpRequest()

  // Convert the parameter object passed by the outside world into a query string
  var qs = resolveData(options.data)
  // Register to listen
  xhr.onreadystatechange = function () {
    // Register to listen
    if (xhr.readyState === 4 && xhr.status === 200) {
      // Convert the server's json string into a js object
      var result = JSON.parse(xhr.responseText)
      options.success(result)
    }
  }
}

5. Determine the type of request

Different request types correspond to different operations of the xhr object, so the request type needs to be judged if… else…

if (options.method.toUpperCase() === 'GET') {
  // Initiate a GET request
  xhr.open(options.method, options.url + '?' + qs)
  xhr.send()
} else if (options.method.toUpperCase() === 'POST') {
  // Initiate a POST request
  xhr.open(options.method, options.url)
  xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
  xhr.send(qs)
}

6. New features of XMLHttpRequest Level2

6.1 Disadvantages of the old XMLHttpRequest

  • Only supports the transmission of text data, cannot be used to read and upload files
  • When transmitting and receiving data, there is no progress information, only whether it is completed or not

6.2 New features of XMLHttpRequest Level2

  • You can set the time limit for HTTP requests
  • You can use the FormData object to manage form data
  • Can upload files
  • You can get the progress information of the data transfer

7. Set HTTP request time limit

Sometimes, Ajax operations are time-consuming, and it is impossible to predict how long it will take. If the internet speed is slow, users may have to wait a long time. The new version of the XMLHttpRequest object adds the timeout attribute, which can set the time limit of the HTTP request.

<script>
  var xhr = new XMLHttpRequest()
  // Set the timeout period
  xhr.timeout = 30
  // Set the processing function after the timeout
  xhr.ontimeout = function () {
    console.log('The request timed out!')
  }
  xhr.open('GET', 'https://www.7ix.net:3006/api/getbooks')
  xhr.send()
  xhr.onreadystatechange = function () {
    if (xhr.readyState === 4 && xhr.status === 200) {
      console.log(xhr.responseText)
    }
  }
</script>

8. FormData object manages form data

Ajax operations are often used to submit form data. In order to facilitate form processing, HTML5 has added a new FormData object, which can simulate form operations.

 // 1. Create a new FormData object
 var fd = new FormData()
 // 2. Add form items to FormData
 fd.append('uname', 'zs')
 fd.append('upwd', '123456')
 // 3. Create XHR object
 var xhr = new XMLHttpRequest()
 // 4. Specify the request type and URL address
 xhr.open('POST', 'http://www.7ix.net:3006/api/formdata')
 // 5. Submit the FormData object directly, which is exactly the same as submitting a web form
 xhr.send(fd)

9. FormData object manages form data

The FormData object can also be used to get the value of a web page form. The sample code is as follows.

// Get form elements
var form = document.querySelector('#form1')
// Listen to the submit event of the form element
form.addEventListener('submit', function(e) {
 e.preventDefault()
 // Create a FormData object based on the form form, and automatically fill the form data into the FormData object
 var fd = new FormData(form)
 var xhr = new XMLHttpRequest()
 xhr.open('POST', 'http://www.7ix.net:3006/api/formdata')
 xhr.send(fd)
 xhr.onreadystatechange = function() {}
})

10. Upload files

The new version of XMLHttpRequest object can not only send text messages, but also upload files.

Implementation steps

  • Define the UI structure
  • Verify that the file is selected
  • Append file to FormData
  • Use xhr to initiate a file upload request
  • Listen to the onreadystatechange event

10.1 Define UI structure

<!-- 1. File selection box -->
 <input type="file" id="file1" />
 <!-- 2. Upload button -->
 <button id="btnUpload">upload files</button>
 <br />
 <!-- 3. Display pictures uploaded to the server -->
 <img src="" alt="" id="img" width="800" />

10.2 Verify that the file is selected

// 1. Get the button for uploading files
var btnUpload = document.querySelector('#btnUpload')
// 2. Add click event listener for button
btnUpload.addEventListener('click', function() {
 // 3. Get the selected file list
 var files = document.querySelector('#file1').files
 if (files.length <= 0) {
 return alert('Please select the file to upload!')
 }
 // ...Follow-up business logic
})

10.3 Append files to FormData

// 1. Create FormData object
var fd = new FormData()
// 2. Append file to FormData
fd.append('avatar', files[0])

10.4 Use xhr to initiate a file upload request

// 1. Create xhr object
var xhr = new XMLHttpRequest()
// 2. Call the open function to specify the request type and URL address. Among them, the request type must be POST
xhr.open('POST', 'http://www.7ix.net:3006/api/upload/avatar')
// 3. Initiate a request
xhr.send(fd)

10.5 Listen to the onreadystatechange event

xhr.onreadystatechange = function() {
 if (xhr.readyState === 4 && xhr.status === 200) {
     var data = JSON.parse(xhr.responseText)
     if (data.status === 200) { // File uploaded successfully
     // Set the image address returned by the server as the src attribute of the <img> tag
        document.querySelector('#img').src = 'http://www.7ix.net:3006' + data.url
     } else { // Failed to upload file
         console.log(data.message)
     }
 }
}

11. Show file upload progress

Calculate file upload progress. In the new version of the XMLHttpRequest object, you can obtain the upload progress of the file by listening to the xhr.upload.onprogress event. The syntax format is as follows.

// Create XHR object
var xhr = new XMLHttpRequest()
// Listen to the onprogress event of xhr.upload
xhr.upload.onprogress = function(e) {
     // e.lengthComputable is a boolean value indicating whether the currently uploaded resource has a computable length
     if (e.lengthComputable) {
         // e.loaded Bytes transferred
         // e.total Total bytes to be transferred
         var percentComplete = Math.ceil((e.loaded / e.total) * 100)
     }
 }

11.1 Import the required libraries

<link rel="stylesheet" href="./lib/bootstrap.css" />
<script src="./lib/jquery.js"></script>

11.2 Render progress bar based on Bootstrap

<!-- progress bar -->
 <div class="progress" style="width: 500px; margin: 10px 0;">
     <div class="progress-bar progress-bar-info progress-bar-striped active" id="percent" style="width: 0%">
     0%
     </div>
 </div>

11.3 Dynamically set to the progress bar

xhr.upload.onprogress = function(e) {
     if (e.lengthComputable) {
         // 1. Calculate the percentage of the current upload progress
         var percentComplete = Math.ceil((e.loaded / e.total) * 100)
         $('#percent')
         // 2. Set the width of the progress bar
         .attr('style', 'width:' + percentComplete + '%')
         // 3. Show the current upload progress percentage
         .html(percentComplete + '%')
     }
}

11.4 Monitor the upload completion event

xhr.upload.onload = function() {
     $('#percent')
     // Remove the class style in upload
     .removeClass()
     // Add the uploaded class style
     .addClass('progress-bar progress-bar-success')
}

Leave a Reply