Ajax学习

引入CDN

<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>

第一个代码

axios({
    url:'http://hmajax.itheima.net/api/province'
}).then(result=>{
    console.log(result)
    document.querySelector('div').innerHTML = result.data.list.join('<br>')
}) // 打印省份地址,result接管对象  
axios({
    url:'http://hmajax.itheima.net/api/city',
    params:{ // 查询参数,可以更方便,不采用?+值的方式
        pname:'山西省',
    }
}).then(result=>{
    console.log(result.data.list)
    document.querySelector('div').innerHTML = result.data.list.join('<br>')
}) // 获取目标省份信息

主要结构

本质上是返回一个promise

axios({
    url:'', // 网址
    params:{ // 查询参数
    },
    method: 'post', // 请求方法,默认get获取数据,post提交数据,put修改全部数据,delete删除,patch修改部分数据
    data:{ // 提交数据
        username:'dadwds2',
        password:'21312'
    }
}).then(result=>{ // 获取数据接管对象 
    console.log(result)
}).catch(error=>{ // 捕获错误
    console.log(error)
})

URL(网址)

协议;//域名:端口号/资源路径,如https://hmajax.itheima.net:80/api/province

查询参数时:协议;//域名:端口号/资源路径?参数名1=值1&参数名2=值2 每多一个参数就加一个&和参数名,端口号默认80可不写

请求报文

规定了浏览器发送至服务器内容的格式,在网页开发工具里的网络里查看请求报文源码,可以帮助查看错误

  1. 请求行:请求方法,URL,协议
  2. 请求头:以键值对的格式携带的附加信息,如Content-Type
  3. 空行:分隔请求头,空行之后的是发送给服务器的资源
  4. 请求体:发送的资源

响应报文

规定了服务器返回内容的格式,主要作用是表明是否请求成功,1xx信息,2xx成功,3xx重定向消息,4xx失败,客户端错误,5xx服务端错误

  1. 响应行(状态行):协议、HTTP相应状态码、状态信息
  2. 响应头:以键值对的格式携带的附加信息,如Content-Type
  3. 空行:分隔响应头,空行之后是服务器返回的资源
  4. 响应体:返回的资源

form-serialize插件使用

主要用于一键收集所有表单信息作为对象,引入前需要导入代码

<script src="./form-serialize.js"></script> // 引入文件
let n = document.querySelector('form')  document.querySelector('button').addEventListener('click',function(){ console.log(serialize(n,{hash:true,empty:true})) })
// hash代表是否转化为对象,empty表示是否收集空信息

Bootstrap

引入

<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/js/bootstrap.bundle.min.js" ></script>

例如modal,toast

<button class="btn btn-danger" type="button" 
data-bs-toggle="modal" data-bs-target=".my-box">点击</button> // toggle用来转换,target用来指向目标
<div class="modal my-box" tabindex="-1"> // 引入modal框
    <div class="modal-dialog">
      <div class="modal-content">
        <div class="modal-header">
          <h5 class="modal-title">Modal title</h5>
          <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> // dismiss用来关闭弹框
        </div>          
        <div class="modal-body">
          <p>Modal body text goes here.</p>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
          <button type="button" class="btn btn-primary">Save changes</button>
        </div>
      </div>
    </div>
  </div>
<button class="btn btn-danger" type="button" >点击</button>
<div class="modal my-box" tabindex="-1" style="display: none;">
    <div class="modal-dialog">
      <div class="modal-content">
        <div class="modal-header">
          <h5 class="modal-title">Modal title</h5>
          <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
        </div>
        <div class="modal-body">
          <p>Modal body text goes here.</p>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
          <button type="button" class="btn btn-primary">Save changes</button>
        </div>
      </div>
    </div>
  </div>
<script>
    let box = document.querySelector('.my-box')
    let modal = new bootstrap.Modal(box)
    let n = document.querySelector('[type=button]')
    n.addEventListener('click',function(){
        modal.show()
    })
</script>

上传图片

<div>
    <input type="file" class="upload">
    <img src="" alt="">
</div>
<script>
    document.querySelector('.upload').addEventListener('change', function(e) {
        let n = new FormData();
        n.append('img', e.target.files[0]);
        axios({
            url: '',
            method: 'post',
            data: n
        }).then(res => {
            console.log(res);
            document.querySelector('img').src = res.data.data.url;
        });
    });
</script>

XMLHttpRequest

const xhr = new XMLHttpRequest() // 创建XHR对象
xhr.open('get','https://hmajax.itheima.net/api/province') // 给方法和url,需要给请求方法
xhr.open('get','https://hmajax.itheima.net/api/city?pname=山西省') // 现在查询需要自己拼
xhr.addEventListener('loadend',()=>{
    console.log(JSON.parse(xhr.response))
}) // 监听加载完成事件,接受结果
xhr.send() // 调用send发起请求
let obj = {
    pname:'山西省',
    cname:'晋城市'
} 
let data = new URLSearchParams(obj) //  当有多个访问时可以借此转成查询参数
data = data.toString() // 转成参数1&参数2这种格式
const xhr = new XMLHttpRequest()
xhr.open('get',`https://hmajax.itheima.net/api/area?${data}`)
xhr.addEventListener('loadend',()=>{
    console.log(JSON.parse(xhr.response))
    let data = JSON.parse(xhr.response)
    document.querySelector('div').innerHTML = data.list.join('<br>')
})
xhr.send()

在XHR中post则需要自己写请求头以JSON形式

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

Promise

Promise本身是同步任务,但是.then和.catch方法是回调函数,回调函数是异步任务。Promise有三种状态,pending,fulfilled->.then,rejected->.catch,状态改变后调用关联处理函数

同步异步:

console.log('1')
let p = new Promise((resolve,reject)=>{
    console.log('同步')
    resolve('异步')
})
console.log('2')
p.then(res=>{
    console.log(res)
}) // 结果为 : 1 同步 2 异步

代码使用

const p = new Promise((resolve,reject)=>{
    setTimeout(()=>{
        resolve('模拟功') // 成功调用这个
        console.log('s')
        reject(new Error('错误'))  // 失败调用这个
    })
})
p.then((r)=>{ // resolve进入这个
    console.log(r)
}).catch(e=>{ // reject进入这个
    console.log(e)
})

实际用法捕获是否成功

document.querySelector('button').addEventListener('click',function(){
    const p = new Promise((resolve,reject)=>{
        let xhr = new XMLHttpRequest()
        xhr.open('get','https://hmajax.itheima.net/api/province')
        xhr.addEventListener('loadend',function(){
            // console.log(xhr.response)
            if(xhr.status>=200&&xhr.status<300){
                resolve(JSON.parse(xhr.response))
            }else{
                reject(new Error())
            }
        })
        xhr.send()
    }).then(res=>{
        console.log(res.list)
        document.querySelector('div').innerHTML = res.list.join('<br>')
    }).catch(e=>{
        console.dir(e)
    })
})

解决回调函数地狱(可以使用async)

因为.then返回一个Promise对象,所以可以将axios的嵌套改成链式,比如一层一层嵌套获得山西省-晋城市-城区的信息,这样里面的错误外卖catch不到,可以借用promise来分开写catch错误,并且避免一层错处处修改的情况

let p1 = new Promise((resolve,reject)=>{
    setTimeout(function(){
        resolve('success1')
    },2000)
    // reject(new Error())
})
let p2 = p1.then(res=>{
    console.log(res)
    return new Promise((resolve,reject)=>{
        setTimeout(()=>{
            resolve('success2')
        },1000)
        // reject(new Error())
    })
})
p2.then(res=>{
    console.log(res)
})

Promise.all

p = Promise.all([promise1,promise2,.....])

.all内的所有promise都成功才返回成功,错一个就不会走.then走.catch,适用于需要所有都成功返回再使用的场景

同步代码

逐层执行,需要原地等待结果再继续往下执行

异步代码

调用后耗时,不阻塞代码继续执行,在将来完成时触发一个回调函数

async&await

async写在函数声明前面,将其作为一个异步函数,await写在axios前面,取代then函数,等待promise对象成功状态的结果值;await必须存在于async中

请求数据以及报错

async function gL(){
    try{
        let p = await axios({url:"http://hmajax.it1heima.net/api/province"})
        console.log(p)
    }catch(e){
        console.dir(e)
    }
}

宏任务和微任务

在同步代码执行完后先执行微任务,目前学到的微任务只有Promise的.then方法,因为更接近js引擎所以优先执行

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值