原生AJAX

  1. AJAX簡介:
    • AJAX 全稱 Asynchronous Javascript And XML,就是異步的 JS 和 XML
    • 通過 AJAX 可以再瀏覽器中向服務器發送異步請求,最大優勢:頁面無刷新獲取數據
    • AJAX 不是新的編程語言,而是一種將現有的標準集合在一期使用的新方式
  1. XML簡介:
    • XML 可擴展標記語言
    • XML 被設計用來傳輸和存儲數據
    • XML 和 HTML 類似,不同的是 HTML 仲都是預定義標籤,而 XML 仲沒有預定義標籤,都是自定義標籤,用來表示一些數據
      1
      2
      3
      4
      5
      <student>
      <name>Donald</name>
      <age>18</age>
      <gender>Male</gender>
      </student>
    • 現在已經被 JSON 取代了
      1
      {"name":"Donald", "age":18, "gender":"Male"}
  1. AJAX特點:
    • 優點:
      1. 可以無需刷新頁面而與服務器進行通信
      2. 允許你根據用戶事件來更部分分頁內容
    • 缺點:
      1. 沒有瀏覽史,不能回退
      2. 存在跨域問題(可解決)
      3. SEO 不友好

AJAX基本使用

  1. 核心對象
    XMLHttpRequest - AJAX的所有操作都是用過該對象進行
  1. 使用步驟:

    1. 創建XMLHttpRequest實例對象

      1
      const xhr = new XMLHttpRequest()
    2. 指定發送請求的:方法(methods)和地址(url)

      1
      xhr.open('GET', 'http://127.0.0.1:8080/test_get')
    3. 發送請求

      1
      xhr.send()
    4. 接收數據

      1
      2
      3
      4
      5
      6
      7
      8
      // 綁定監聽狀態
      xhr.onreadystatechange = () => {
      // 當監聽狀態等於 4 表示數據接收完畢
      if(xhr.readyState === 4){
      // xhr.response 獲取數據
      content.innerHTML = `<h3>${xhr.response}</h3>`
      }
      }

xhr內部的五種狀態

  • 5種狀態的值分別為:0、1、2、3、4
    • 0:實例出來的那一刻(初始狀態)
    • 1:open已經調用了,但是send還沒有調用,此時可以修改請求頭內容
    • 2:send已經調用了,已經無法修改請求頭
    • 3:已經回來一部分數據,小的數據會在此階段一次性接收完畢,較大的數據有待進一步接收,響應頭一定回來
    • 4:數據全部接收完畢

GET請求

  1. 攜帶query參數

    1. 指定請求:

      • 使用query參數 (urlencoded) 編碼形式:key=value&key=value
        1
        xhr.open('GET', 'http://127.0.0.1:8080/test_get?name=Donald&age=18')
    2. 接收參數:

      • 使用request.query屬性
        1
        2
        3
        app.get('/test_get/', (request, response) => {
        console.log(request.query)
        })
  1. 攜帶params參數

    1. 指定請求:

      • 使用params參數形式:xxx/xxx/Donald/18
        1
        xhr.open('GET', 'http://127.0.0.1:8080/test_get/Donald/18')
    2. 接收參數:

      • 使用request.params屬性
      • 地址配置佔位符 (/:name/:age)
        1
        2
        3
        4
        // 佔位符
        app.get('/test_get/:name/:age', (request, response) => {
        console.log(request.params)
        })

POST請求

  1. 攜帶query參數

    1. 指定請求:

      • 使用query參數 (urlencoded) 編碼形式
        1
        xhr.open('POST', 'http://127.0.0.1:8080/test_post?name=Donald&age=18')
    2. 接收參數:

      • 使用request.query屬性
        1
        2
        3
        app.post('/test_post/', (request, response) => {
        console.log(request.query)
        })
  1. 攜帶params參數

    1. 指定請求:

      • 使用params參數形式
        1
        xhr.open('POST', 'http://127.0.0.1:8080/test_post/Donald/18')
    2. 接收參數:

      • 使用request.params屬性
      • 地址配置佔位符 (/:name/:age)
        1
        2
        3
        4
        // 佔位符
        app.post('/test_post/:name/:age', (request, response) => {
        console.log(request.params)
        })
  1. 使用請求體的urlencode編碼形式

    1. 指定請求:

      • 不需要在地址中添加
        1
        xhr.open('POST', 'http://127.0.0.1:8080/test_post')
    2. 追加響應頭:

      • 用於表示攜帶請求體參數的urlencode編碼形式
        1
        xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded')
    3. 發送請求:

      • 在發送請求時傳入參數
        1
        xhr.send('name=Donald&age=18')
    4. 使用中間件解析:

      • 引入中間件解析urlencoded編碼形式的請求體參數
        1
        app.use(express.urlencoded({extended:true}))
    5. 接收參數:

      • 使用request.body屬性
        1
        2
        3
        app.post('/test_post', (request, response) => {
        console.log(request.body)
        })
  1. 使用請求體的json編碼形式

    1. 指定請求:

      • 不需要在地址中添加
        1
        xhr.open('POST', 'http://127.0.0.1:8080/test_post')
    2. 追加響應頭:

      • 用於表示攜帶請求體參數的json編碼形式
        1
        xhr.setRequestHeader('Content-type', 'application/json')
    3. 發送請求:

      • 在發送請求時傳入參數
      • JSON.stringify對象,讓其轉換為JSON字符串
        1
        2
        const person = {name:'Donald', age:18}
        xhr.send(JSON.stringify(person))
    4. 使用中間件解析:

      • 引入中間件解析json編碼形式的請求體參數
        1
        app.use(express.json())
    5. 接收參數:

      • 使用request.body屬性
        1
        2
        3
        app.post('/test_post', (request, response) => {
        console.log(request.body)
        })

解析JSON數據

  1. 解析JSON格式數據:
    • 在獲取數據之後使用JSON.parse函數解析
      1
      2
      const result = JSON.parse(xhr.response)
      console.log(result)
    • 問題:如果服務器返回的數據非 JSON 格式則會報錯
  1. xhr的API解析JSON格式:
    • 配置xhr.responseType屬性為json
      1
      xhr.responseType = 'json'
    • 服務器返回數據後就會進行 JSON 格式的解析,如果返回數據非 JSON 格式則response為null

請求異常與超時處理

  1. 處理請求異常:
    • 使用xhr.onerror配置請求異常的回調函數
      1
      2
      3
      xhr.onerror = () => {
      alert('Request Error')
      }
  1. 處理超時問題:
    • 使用xhr.timeout設置請求時限,如果超過時限則取消請求
    • 使用xhr.ontimeout配置超時的回調函數
      1
      2
      3
      4
      5
      6
      7
      // 超時時間
      xhr.timeout = 2000

      // 超時的回調
      xhr.ontimeout = () => {
      alert('Request Timeout');
      }

取消請求

  1. 取消請求:
    • 使用xhr.abort函數可以取消該次請求
      1
      xhr.abort()
  1. 工作原理:
    • 測試編碼:
      1
      2
      xhr.send()
      xhr.abort()
    • 如果發送請求之後立即取消請求,該次請求是有可能已經發送到服務器,但也獲取不到數據,因為瀏覽器會將服務器的響應攔截
    • 簡而言之,然後速度夠快,在請求沒有發送到服務器之前被攔截並取消,如果請求發送到服務器,那麼瀏覽器也會攔截服務器的響應

避免多次重複請求

  • 配置一個isLoading屬性判斷請求是否發送中,如果發送中,再次發生請求則關閉上次的請求
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    let xhr
    let isLoading
    btn.onclick = () => {
    if(isLoading) xhr.abort() // 如果發送請求中則取消該次請求
    xhr.onreadystatechange = () => {
    if(xhr.readyState === 4 && (xhr.status >= 200 && xhr.status < 300)){
    isLoading = false // 接收到數據後為 false
    }
    }
    xhr.send()
    isLoading = true // 發生請求後為 true
    }

jQuery

GET請求

  1. 完整版:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    $.ajax({
    url: 'http://127.0.0.1:8080/test_jquery_get', // 請求地址
    method: 'GET', // 請求方式(默認值GET)
    dataType: 'json', // 配置響應數據格式
    data: {}, // 攜帶的數據
    timeout: 2000, // 指定超時時間
    success: (result, responseText, xhr) => { // 成功的回調
    result // 服務器的響應數據
    responseText // 響應結果 (success)
    xhr // xhr 構造函數
    },
    error: () => {}, // 失敗的回調
    })
  1. 精簡版:
    1
    2
    3
    $.get('http://127.0.0.1:8080/test_jquery_get', {}, (data) => {
    console.log(data)
    },'json')
  1. 備註:攜帶的數據默認是query格式,可以使用params格式,不過要在url和服務器追加上追加

POST請求

  1. 完整版:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    $.ajax({
    url: 'http://127.0.0.1:8080/test_jquery_post', // 請求地址
    method: 'POST', // 請求方式(默認值GET)
    dataType: 'json', // 配置響應數據格式
    data: {}, // 攜帶的數據
    timeout: 2000, // 指定超時時間
    success: (result, responseText, xhr) => { // 成功的回調
    result // 服務器的響應數據
    responseText // 響應結果 (success)
    xhr // xhr 構造函數
    },
    error: () => {}, // 失敗的回調
    })
  1. 精簡版:
    1
    2
    3
    $.post('http://127.0.0.1:8080/test_jquery_post', {}, (data) => {
    console.log(data)
    },'json')
  1. 備註:攜帶的數據默認是query格式,可以使用params格式,不過要在url和服務器追加上追加