本文介绍: 【代码】JavaScript-XHR-深入理解

1. XHR(Asynchronous JavaScript And XML)初始

1.1. xhr request demo

<!DOCTYPE html&gt;
<html lang="en"&gt;
<head&gt;
  <meta charset="UTF-8"&gt;
  <meta http-equiv="X-UA-Compatible" content="IE=edge"&gt;
  <meta name="viewport" content="width=device-width, initial-scale=1.0"&gt;
  <title&gt;JS-learn</title&gt;
</head&gt;
<body&gt;
    <button class="dataClick">get data</button>
    <p></p>
    <textarea class="dataArea"></textarea>
  
  <script>

    const buttonData = document.querySelector(".dataClick");
    const dataInput = document.querySelector(".dataArea")
    // debugger
    buttonData.onclick = function getData(){
        // 1. create XMLHttpRequest object
        const xhr = new XMLHttpRequest()

        // 2. monitor the change of status (macrotask)
        xhr.onreadystatechange = () => {
            if (xhr.readyState !== XMLHttpRequest.DONE) return

            // get the response data
            const resJSON = JSON.parse(xhr.response)
            console.log('response: ', resJSON)
            // data = resJSON
            dataInput.value = JSON.stringify(resJSON)
        }

        // 2. configure request open
        xhr.open('get', 'http://123.xxx:8000/home/multidata')

        // 4. send request
        xhr.send()
    }

  </script>
</body>
</html>

1.2. status of XHRHttpRequest

Y
在这里插入图片描述
在这里插入图片描述

1.3. send synchronous request by xhr

<!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>JS-learn</title>
</head>
<body>
    <button class="dataClick">get data</button>
    <button class="clearClick">clear</button>
    <p></p>
    <textarea class="dataArea"></textarea>
  
  <script>

    const buttonData = document.querySelector(".dataClick");
    const dataInput = document.querySelector(".dataArea")
    const clearData =  document.querySelector(".clearClick")
    // debugger
    buttonData.onclick = function getData(){
        // 1. create XMLHttpRequest object
        const xhr = new XMLHttpRequest()

        // 2. monitor the change of status (macrotask)
        xhr.onreadystatechange = () => {
            if (xhr.readyState !== XMLHttpRequest.DONE) {
              console.log(xhr.readyState)
              return
            }

            // get the response data
            const resJSON = JSON.parse(xhr.response)
            console.log('response: ', resJSON)
            console.log('status: ', xhr.status)
            console.log('xhr: ', xhr)
            // data = resJSON
            dataInput.value = JSON.stringify(resJSON)
        }

        // 2. configure request open
        xhr.open('get', 'http://xxxx.32:8000/home/multidata', true)

        // 4. send request
        xhr.send()

        console.log('here is the log after sending')
    }
    clearData.onclick = () => {
        dataInput.value = ""
    }

  </script>

</body>
</html>

在这里插入图片描述

        // 2. configure request open
        xhr.open('get', 'http://123.207.32.32:8000/home/multidata', false)

在这里插入图片描述

1.4. onload监听数据加载完成

<!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>JS-learn</title>
</head>
<body>
    <button class="dataClick">get data</button>
    <button class="clearClick">clear</button>
    <p></p>
    <textarea class="dataArea"></textarea>
  
  <script>

    const buttonData = document.querySelector(".dataClick");
    const dataInput = document.querySelector(".dataArea")
    const clearData =  document.querySelector(".clearClick")
    // debugger
    buttonData.onclick = function getData(){
        // 1. create XMLHttpRequest object
        const xhr = new XMLHttpRequest()

        // 2. monitor onload event
        xhr.onload = () => {
            console.log('onload')
            dataInput.value = xhr.response
        }

        // 2. configure request open
        xhr.open('get', 'http://xxx.32:8000/home/multidata', false)

        // 4. send request
        xhr.send()
    }
    clearData.onclick = () => {
        dataInput.value = ""
    }

  </script>

</body>
</html>

1.5. http status 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>JS-learn</title>
</head>
<body>
    <button class="dataClick">get data</button>
    <button class="clearClick">clear</button>
    <p></p>
    <textarea class="dataArea"></textarea>
  
  <script>

    const buttonData = document.querySelector(".dataClick");
    const dataInput = document.querySelector(".dataArea")
    const clearData =  document.querySelector(".clearClick")
    // debugger
    buttonData.onclick = function getData(){
        // 1. create XMLHttpRequest object
        const xhr = new XMLHttpRequest()

        // 2. monitor onload event
        xhr.onload = () => {
            console.log(xhr.status, xhr.statusText)
            // make a judgement based on http status code
            if (xhr.status >= 200 &amp;&amp; xhr.status < 300) {
                console.log('get response success: ', xhr.response)
            } else {
              console.log(xhr.status, xhr.statusText)
            }
            dataInput.value = xhr.response
        }

        xhr.onerror = () => {
          console.log('send request error: ', xhr.status, xhr.statusText)
        }

        // 2. configure request open
        xhr.open('get', 'http://xxx.32:8000/home/mudltidata', false)

        // 4. send request
        xhr.send()
    }
    clearData.onclick = () => {
        dataInput.value = ""
    }

  </script>

</body>
</html>

在这里插入图片描述

1.6. get/post request with josn/form/urlcoded

<!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>JS-learn</title>
</head>
<body>
    <button class="dataClick">get data</button>
    <button class="clearClick">clear</button>
    <p></p>
    <textarea class="dataArea"></textarea>
    <form class="info">
      <input type="text" name="username">
      <input type="password" name="password">
    </form>
    <p></p>
    <button class="send">send request</button>
  
  <script>

    const buttonData = document.querySelector(".dataClick");
    const dataInput = document.querySelector(".dataArea")
    const clearData =  document.querySelector(".clearClick")


    const formEl = document.querySelector(".info")
    const sendBtn = document.querySelector(".send")
    // debugger
    sendBtn.onclick = function getData(){
        // 1. create XMLHttpRequest object
        const xhr = new XMLHttpRequest()

        // 2. monitor onload event
        xhr.onload = () => {
            console.log(xhr.status, xhr.statusText)
            // make a judgement based on http status code
            if (xhr.status >= 200 &amp;&amp; xhr.status < 300) {
                console.log('get response success: ', xhr.response)
            } else {
              console.log(xhr.status, xhr.statusText)
            }
            dataInput.value = xhr.response
        }

        xhr.onerror = () => {
          console.log('send request error: ', xhr.status, xhr.statusText)
        }

        // 2. configure request open
        // 2.1. http get
        // xhr.open('get', 'http://xxx.32:1888/02_param/get?name=michael&amp;age=18&amp;address=广州市')
        // xhr.send()

        // 2.2. post: urlencoded
        // xhr.open('post', 'http://xxx.32:1888/02_param/posturl')
        // xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded')
        // xhr.send('name=michael&amp;age=18&amp;address=广州市')

        // 2.3. post: formdata
        // xhr.open('post', 'http://xxx.32:1888/02_param/postform')
        // const formData = new FormData(formEl)
        // xhr.send(formData)

        // 2.4. post: json
        xhr.open('post', 'http://xxx.32:1888/02_param/postjson')
        xhr.setRequestHeader('Content-type', 'application/json')
        xhr.send(JSON.stringify({name: "michael", age:18, height: 1.8}))

        // 4. send request
        // xhr.send()
    }
    clearData.onclick = () => {
        dataInput.value = ""
    }

  </script>

</body>
</html>

1.7. encapsulate an ajax function to send requests

<!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>JS-learn</title>
</head>
<body>
    <button class="send">send request</button>
  
  <script>

    // my ajax request class
    function myAjax({
      url,
      method = 'get',
      data = {},
      headers = {},
      success,  // callback function after sending requeset successfully
      failure   // callback function where there is any error 
    } = {}){
      // 1. create a XMLHttpRequeset
      const xhr = new XMLHttpRequest()

      //  2. monitor the data
      xhr.onload = function() {
        if (xhr.status >= 200 &amp;& xhr.status < 300) {
          success && success()
        } else {
          failure && failure({status: xhr.status, message: xhr.statusText})
        }
      }

      // 3. set the response type
      xhr.responseType = 'json'

      // 4. configure open
      if (method.toUpperCase() === 'GET') {
        const queryStr = []
        for (const key in data) {
          queryStr.push(`${key}=${data[key]}`)
        }

        url = url + '?' + queryStr.join('&')
        xhr.open(method, url)
        xhr.send()
      }else {
        xhr.open(method, url)
        xhr.setRequestHeader('Content-type', 'application/json')
        xhr.send(JSON.stringify(data))
      }

      return xhr

    }

    const sendBtn = document.querySelector(".send")
    
    // sendBtn.onclick = function getData(){
    //   myAjax({
    //     url: "http://xxx.32:1888/02_param/gest",
    //     method: "GET",
    //     data: {
    //       name: "michael",
    //       age: 18
    //     },
    //     success: function(res) {
    //       console.log("res:", res)
    //     },
    //     failure: function(err) {
    //       alert(err.message)
          
    //     }
    //   })
    // }
    sendBtn.onclick = function getData(){
      myAjax({
        url: "http://xxx.32:1888/02_param/postjson",
        method: "post",
        data: {
          name: "michael",
          age: 18
        },
        success: function(res) {
          console.log("res:", res)
        },
        failure: function(err) {
          alert(err.message)
          
        }
      })
    }
  </script>

</body>
</html>

1.8. encapsulate an ajax function to send requests with Promise

function myAjax({
    url,
    method = "get",
    data = {},
    timeout = 10000,
    headers = {}, // token 
} = {}) {
    // 1. create a XMLHttpRequest object
    const xhr = new XMLHttpRequest()

    // 2. create a promise object
    const promise = new Promise((resolve, reject) => {

        // 3. monitor data
        xhr.onload = function() {
            if (xhr.status >= 200 && xhr.status < 300) {
                resolve(xhr.response)
            } else {
                reject({ status: xhr.status, message: xhr.statusText })
            }
        }

        // 4. set response type and timeout
        xhr.responseType = 'json'
        xhr.timeout = timeout

        // 5. configure open
        if (method.toUpperCase() === 'GET') {
            const queryStr = []
            for (const key in data) {
                queryStr.push(`${key}&${data[key]}`)
            }
            url = url + '?' + queryStr.join('&')
            xhr.open(method, url)
            xhr.send()
        } else {
            xhr.open(method, url)
            xhr.setRequestHeader('Content-type', 'application/json')
            xhr.send(JSON.stringify(data))
        }
    })

    promise.xhr = xhr

    return promise
}

2. Fetch

2.1. fetch demo

<!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>Fetch</title>
</head>
<body>
    <button class="send">send request</button>
    <script>

        const sendBtn = document.querySelector('.send')
        // 1. fetch send http request
        // sendBtn.onclick = () => {
        //     fetch('http://xxx.32:8000/home/multidata').then(result => {
        //         console.log(result)
        //     }).catch(reason => {
        //         console.log(reason)
        //     })
        // }

        // 2. optimize code when using fetch
        // 2.1. first solution
        // sendBtn.onclick =  () => {
        //     fetch('http://xxx.32:8000/home/multidata').then(result => {
        //         return result.json()
        //     }).then(result => {
        //         console.log('result: ', result)
        //     }).catch(reason => {
        //         console.log('error: ', reason)
        //     })
        // }

        // 2.2. second solution
        // async function getData(){
        //     const response = await fetch('http://xxx.32:8000/home/multidata')
        //     const result = await response.json()
        //     console.log('result: ', result)
        // }

        // sendBtn.onclick = getData

        // 3. send post request with params
        // 3.1. send json 
        // async function getData() {
        //     const response = await fetch('http://xxx.32:1888/02_param/postjson', {
        //         method: 'post',
        //         headers: { 'Content-type': 'application/json' },
        //         body: JSON.stringify({
        //             name: 'michael',
        //             age: 18
        //         })
        //     })

        //     console.log(response.ok, response.status, response.statusText)
        //     const result = await response.json()
        //     console.log('result: ', result)

        // }

        // sendBtn.onclick = getData

        // 3.2. send form
        async function getDate() {
            const formData = new FormData()
            formData.append('name', 'michael')
            formData.append('age', 18)
            const response = await fetch('http://xxxx.32:1888/02_param/postform', {
                method: 'post',
                body: formData
            })

            console.log(response.ok, response.status, response.statusText)

            const result = await response.json()
            console.log('result: ', result)
        }
        sendBtn.onclick = getDate

    </script>
</body>

原文地址:https://blog.csdn.net/weixin_46036165/article/details/129143072

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任

如若转载,请注明出处:http://www.7code.cn/show_22248.html

如若内容造成侵权/违法违规/事实不符,请联系代码007邮箱:suwngjj01@126.com进行投诉反馈,一经查实,立即删除

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注