Ajax review 02-(form, axios interceptor, FormData file upload)

What is a form

In web pages, forms are mainly responsible for data collection.

The three components of a form

The form for collecting data in the web page consists of three parts: form label, form field and form button.

Form label

The HTML form is a "container" used to delimit the specified area on the page as the form area

Form field

Form fields provide channels for collecting user information. Common form fields include input, textarea, select, etc

Note: each form field must contain the name attribute, otherwise the information filled in by the user cannot be collected!

Form button

When the form data is filled in, the user clicks the form button to trigger the form submission operation, so as to submit the collected data to the server.

be careful:

① type="submit" means submit button

② The default value of the type attribute is submit, so type="submit" can be omitted

Properties of the form tag

The three most important attributes of the form tag are action, method and enctype.

Submit form data in GET mode

On the form tag, specify the URL address of submission through the action attribute, and specify the submission method as GET through the method attribute

Note: since the default value of the method attribute is GET, the above method="GET" can be omitted!

   <form action="http://www.liulongbin.top:3009/api/form" method="get">
    full name: <input type="text" name="username"><br>
    password: <input type="password" name="password"><br>
    <button type="submit">Submit</button>
  </form>

Submit form data by POST

On the form tag, specify the URL address of submission through the action attribute, the submission method through the method attribute as POST, and the encoding method of data through the enctype attribute as application/x-www-form-urlencoded

Note: since the default value of enctype is application/x-www-form-urlencoded, the above enctype can be omitted!

   <form action="http://www.liulongbin.top:3009/api/form" method="post" enctype="application/x-www-form-urlencoded">
    full name: <input type="text" name="username"><br>
    password: <input type="password" name="password"><br>
    <button type="submit">Submit</button>
  </form>

The difference between the three optional values of enctype

form submission questions

1. Causes of problems:

Form table detail and several positions: responsible for collecting data and submitting data to the server. The default submission behavior of the form will cause the page to jump.

2. Solution:

form is only responsible for collecting data; Ajax is responsible for submitting data to the server.

Submit form data through Ajax

The data collected by submitting the form through Ajax can prevent the page Jump caused by the default submission behavior of the form and improve the user experience.

① Listen to the submit event of the form

② Block default commit behavior

③ Initiate request based on axios

④ Specify request method and address

⑤ Specify request body data

<body>
  <form action="">
    full name: <input type="text" name="username"><br>
    password: <input type="password" name="password"><br>
    <button type="submit">Submit</button>
  </form>
​
  <script src="./lib/jquery.js"></script>
  <script src="./lib/axios.js"></script>
  <script>
    // 1. Listen for form submission events
    $('form').on('submit', function (e) {
      // 2. Submission of organizational events
      e.preventDefault()
      // 3.ajax submits data, and the form does not need to submit data Benefit: the page will not jump
      axios({
        // 4. Specify the request method and address
        method: 'post',
        url: 'http://www.liulongbin.top:3009/api/form',
        // 5. Specify request body data
        data: {
          username: $('[name="username"]').val(),
          password: $('[name="password"]').val()
        },
      }).then(({data: res}) => {
        console.log(res)
      })
    })
  </script>
</body>

serialize() function of jQuery

The serialize() function of jQuery can get the data collected in the form at one time

Note: when using the serialize() function to quickly obtain form data, you must add the name attribute for each form field!

<body>
  <form action="">
    full name: <input type="text" name="username"><br>
    password: <input type="password" name="password"><br>
    <button type="submit">Submit</button>
  </form>
​
  <script src="./lib/jquery.js"></script>
  <script src="./lib/axios.js"></script>
  <script>
    $('form').on('submit', function (e) {
      e.preventDefault()
      axios({
        method: 'post',
        url: 'http://www.liulongbin.top:3009/api/form',

        data: $(this).serialize()
      }).then(({data: res}) => {
        console.log(res)
      })
    })
  </script>
</body>

Alias of axios request method

axios. Usage of get()

<body>
  <button>get Request without parameters</button>
  <button>get Request with parameters</button>
  <!-- 1.introduce axios.js library -->
  <script src="./lib/axios.js"></script>
  <script src="./lib/jquery.js"></script>
  <script>
    // Axios get send request
    $('button').eq(0).click(function () {
      axios.get('http://www.liulongbin.top:3009/api/get').then(({
        data: res
      }) => {
        console.log(res)
      })
    })
​
    // Axios get (address, {params: value}) send request with parameters
    $('button').eq(1).click(function () {
      axios.get('http://www.liulongbin.top:3009/api/get', {
        params: {
          name: 'jack',
          age: 18
        }
      }).then(({
        data: res
      }) => {
        console.log(res)
      })
    })
  </script>
</body>

axios. Usage of post()

<body>
  <button>post Request without parameters</button>
  <button>post Request with parameters</button>
  <!-- 1.introduce axios.js library -->
  <script src="./lib/axios.js"></script>
  <script src="./lib/jquery.js"></script>
  <script>
    // Axios post (address) send request
    $('button').eq(0).click(function () {
      axios.post('http://www.liulongbin.top:3009/api/post').then(({
        data: res
      }) => {
        console.log(res)
      })
    })
​
    // Axios post (address, parameter value) send request with parameters
    $('button').eq(1).click(function () {
      axios.post('http://www.liulongbin.top:3009/api/post', {
        name: 'jack',
        age: 18
      }).then(({
        data: res
      }) => {
        console.log(res)
      })
    })
  </script>
</body>

Global configuration request root path

In the url address, the part corresponding to protocol: / / Domain Name: port is called "request root path".

Benefits of global configuration request root path: improving project maintainability

Based on the fixed configuration provided by axios, the root path of the request can be easily configured. The syntax format is as follows: axios defaults. Baseurl = 'request root path'

<body>
  <button>get Request without parameters</button>
  <button>get Request with parameters</button>
  <!-- 1.introduce axios.js library -->
  <script src="./lib/axios.js"></script>
  <script src="./lib/jquery.js"></script>
  <script>
    // Set the global request root path (all URL s in the baseURL are capitalized)
    axios.defaults.baseURL = 'http://www.liulongbin.top:3009'
    
    // When calling the interface, only "specific request path" is provided
    $('button').eq(0).click(function () {
      axios.get('/api/get').then((res) => {
        console.log(res)
      })
    })
​
    // When calling the interface, only "specific request path" is provided
    $('button').eq(1).click(function () {
      axios.post('/api/post', {
        name: 'jack',
        age: 18
      }).then((res) => {
        console.log(res)
      })
    })
  </script>
</body>

axios interceptor

What is an interceptor

interceptors are used to globally intercept every request and response of axios.

Benefits: some repetitive business codes in each request can be encapsulated in the interceptor to improve the reusability of the code.

Use interceptor - achieve loading effect

// Request interception
axios.interceptors.request.use(function (config) {
  // What to do before sending the request
  // Show loading effect
  $('.loading-box').show()
  return config
}, function (error) {
  // What to do about request errors
  return Promise.reject(error)
})
​
// Response interception
axios.interceptors.response.use(function (response) {
  // What do you do in response to data
  // Hide loading effect
  $('.loading-box').hide()
  return response
}, function (error) {
  // What to do with response errors
  // Hide loading effect
  $('.loading-box').hide()
  return Promise.reject(error)
})

File upload

FormData

Concept: FormData is a web API provided by the browser, which stores data in the form of key value pairs.

Function: with Ajax technology, FormData can send request body data in multipart / form data format to the server.

Typical application scenario: FormData + Ajax technology realizes the function of file upload.

Note: when uploading Ajax files, the encoding format of the request body must be multipart / form data.

Basic usage of FormData

FormData is a constructor. new FormData() can get the FormData object:

let fd = new FormData() / / create a blank FormData object that does not contain any data.
Let FD = new formdata (form object)

Call the append (key, value) method of the FormData object to append key value pair data to the blank FormData, where:

The key represents the name of the data item and must be a string

The value represents the value of the data item and can be any type of data

fd.append('username ',' Zhang San ') / / the key is username and the value is string type
 fd.append('age ', 20) / / the key is age and the value is numeric
 fd.append('avatar ', image file) / / the key is Avatar, and the value is the file type

Send normal FormData data

FormData + axios submit normal data to the server (excluding file upload)

<body>
  <button>send out</button>
  <script src="./lib/axios.js"></script>
  <script>
    document.querySelector('button').onclick = function () {
      // 1. Create a blank FormData object that does not contain any data
      let fd = new FormData()
​
      // 2. Add data to fd
      fd.append('username', 'jack') 
      fd.append('age', 18) 
​
      // 3. Use axios to submit the request body data in FormData format to the server
      axios.post('http://www.liulongbin.top:3009/api/formdata',fd).then((data: res)=>{
        console.log(res)
      })
    }
  </script>
</body>

Keywords: Javascript html Ajax

Added by HHawk on Wed, 19 Jan 2022 02:56:35 +0200