AJAX的四種方式(原生JS & jQuery & axios & fetch)

一、原生AJAX

1、GET請求

GET請求的參數(shù),使用?直接拼接在url地址后面,如果有多個(gè)參數(shù)使用&符號。
參數(shù)例如:name=${name}&pageIndex=${pageIndex}

// 01.創(chuàng)建xhr對象
let xhr = new XMLHttpRequest()
// 02.初始化請求
xhr.open('GET',`http://localhost:5566/students?name=${name}`)
// 03.發(fā)送請求
xhr.send()
// 04.監(jiān)聽事件,并接收結(jié)果
xhr.onreadystatechange = function(){
     //請求完成
     if(xhr.readyState===4){
         //請求成功
         if(xhr.status===200){      
            console.log(xhr.response);   //打印響應(yīng)結(jié)果
         }
     }
 }

2、POST請求

(1)設(shè)置Content-Type請求頭

POST請求時(shí),需要設(shè)置Content-Type請求頭,告訴服務(wù)器傳遞的數(shù)據(jù)格式。
如果是urlencoded格式的數(shù)據(jù):

xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded")

如果是json字符串格式的數(shù)據(jù):

xhr.setRequestHeader('Content-Type','application/json')

(2)參數(shù)傳遞

post請求的參數(shù),在發(fā)送時(shí)傳遞。
傳遞urlencoded格式的數(shù)據(jù):

xhr.send(`name=polo&age=35`)

傳遞json字符串格式的數(shù)據(jù):

let params = {
     name:name,
     hobbies:hobbies.split(',')   //愛好,轉(zhuǎn)為數(shù)組
 }
xhr.send(JSON.stringify(params))   // 將對象轉(zhuǎn)為json格式字符串

(3)基本格式

  let xhr = new XMLHttpRequest()
  xhr.open('POST','http://localhost:5566/deleteStudent')
  xhr.setRequestHeader('Content-Type','application/json')
  xhr.send(JSON.stringify({_id:id}))
  xhr.onreadystatechange = function(){
      if(xhr.readyState===4){
          if(xhr.status===200){
                console.log(xhr.response);
          }
      }
}

二、jQuery AJAX

1、GET請求

語法:$.get(請求地址, {參數(shù)名: 參數(shù)值}, 回調(diào)函數(shù))

  $.get('http://localhost:5566/students',{name:"張三"},r=>{
        console.log(r);    // r表示請求成功時(shí)返回的結(jié)果數(shù)據(jù)
  })

2、POST請求

語法:$.post(請求地址, {參數(shù)名: 參數(shù)值}, 回調(diào)函數(shù))

  $.post('http://localhost:5566/deleteStudent',{_id:id},r=>{
        console.log(r);    // r表示請求成功時(shí)返回的結(jié)果數(shù)據(jù)       
  })

3、通用型方法ajax

(1)get請求

            $.ajax({
                type: "get",   // 請求的接口地址
                url: url,      // 請求方式get 或 post
                dataType: "json", // 返回的數(shù)據(jù)類型
                // 請求成功后的回調(diào)函數(shù)
                success: function (r) {
                    console.log(r)
                },
                // 請求失敗后調(diào)用的函數(shù)
                error: function (err) {
                    console.log('請求錯(cuò)誤')
                }
            });

(2)post請求

發(fā)送post請求時(shí),如果請求參數(shù)是json字符串格式,需要設(shè)置contentType請求頭為'application/json'。contentType默認(rèn)值 "application/x-www-form-urlencoded"

let params = {
         name:name,
         hobbies:hobbies.split(',') 
   }
$.ajax({
         url:url,       // 請求的接口地址
         type:'POST',   // 請求方式get 或 post
         data:JSON.stringify(params),   // 請求的參數(shù)
         contentType:'application/json',
         success:function(r){
             console.log(r);   // r表示請求成功時(shí)返回的結(jié)果數(shù)據(jù)
         }
    })

三、axios AJAX

1、引入axios庫

axios庫MDN地址

<script src="https://cdn.bootcdn.net/ajax/libs/axios/0.21.1/axios.js"></script>

2、GET請求

(1)get請求的參數(shù)可以直接用?拼接在URL中

        axios.get('http://localhost:5566/user?ID=12345').then(function (response) {
            console.log(response);
        }).catch(function (error) {
            console.log(error);
        });

(2)get請求的參數(shù)可以寫在params對象中

注意:請求返回結(jié)果包含很多信息,需要將結(jié)果中的data解構(gòu)出來。data中存放的才是需要的數(shù)據(jù)。

      axios.get('http://localhost:5566/students', {
            params: {
               name:name
           }
      }).then(({ data }) => {   
           console.log(data)
      })

3、POST請求

post請求參數(shù)直接寫在對象中傳入。

axios.post(`http://localhost:5566/deleteStudent`, {
      name:name,
      hobbies:hobbies.split(','),
 }).then(({ data }) => {   
         console.log(data)
})

4、通用方式axios

  axios({     
      method: 'POST',   //請求方法           
      url: '/axios-server',    //url           
      params: {     //請求參數(shù)
          vip: 10,
          level: 30
      },           
      headers: {  //設(shè)置請求頭信息
          a: 100,
          b: 200
      },
      //請求體參數(shù)
      data: {
          username: 'admin',
          password: 'admin'
      }
  }).then(response => {
      console.log(response);
      //響應(yīng)狀態(tài)碼
      console.log(response.status);
      //響應(yīng)狀態(tài)字符串
      console.log(response.statusText);
      //響應(yīng)頭信息
      console.log(response.headers);
      //響應(yīng)體
      console.log(response.data);
  })

四、fetch AJAX

1、fetch定義

fetch是一個(gè)瀏覽器內(nèi)置的全新的請求API。之前我們使用的jquery和axios的請求方法只是對XMLHttpRequest對象的封裝。
fetch()函數(shù)的第一個(gè)參數(shù)是url地址,第二個(gè)參數(shù)是配置對象。

2、GET請求

GET請求的參數(shù),使用?直接拼接在url地址后面,如果有多個(gè)參數(shù)使用&符號。

fetch(`http://localhost:5566/students?stuName=${stuName}`,{
      method:'GET',    //設(shè)置請求方式(默認(rèn)是GET)
 }).then(response=>{
    // 第一個(gè)then,用于返回請求的狀態(tài)信息(檢查請求是否成功等等)
    // 再通過請求狀態(tài)對象的.json()方法,返回請求結(jié)果
     return response.json()
 }).then(r =>{
     console.log(r)   // 返回請求結(jié)果
 })

3、POST請求

發(fā)送post請求時(shí),請求參數(shù)如果是json字符串格式,需要配置請求頭headers,設(shè)置Content-Type為'application/json'。

  let params = {
      name:name,
      hobbies:hobbies.split(','),
  }
  fetch(url,{
      method:'POST',
      //配置請求頭信息
      headers:{
          'Content-Type':'application/json'
      },
      body:JSON.stringify(params)   // post請求參數(shù)
  }).then(r=>{
      return r.json()
  }).then(r=>{
      console.log(r)   // 返回請求結(jié)果
  })
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容