首页 > 编程语言 >Ajax学习-黑马程序员视频教程-001

Ajax学习-黑马程序员视频教程-001

时间:2024-05-21 22:08:19浏览次数:27  
标签:xml const state res Ajax 001 console data 视频教程

黑马程序员视频链接

查询参数params

 axios({
    url:'http://hmajax.itheima.net/api/city',
    params: {
        pname: '河北省'
    }
 }).then(res => {
    console.log(res);
    state.mainDataLiat = res.data.list
 })

一个简单案例(用vue3)

<template>
    <div class="flex">
        <span>省:</span>
        <el-input v-model="state.pname" style="width: 200px;"></el-input>
    </div>
    <div class="flex">
        <span>市:</span>
        <el-input v-model="state.cname" style="width: 200px;"></el-input>
    </div>
    <el-button @click="handleSearch" type="primary">查询</el-button>
    <h5 v-for="item in state.mainDataLiat">{{ item }}</h5>

 </template>
 
 <script setup name="Model" lang="ts">
 import { reactive } from 'vue'
 import axios from 'axios';

 let state = reactive({
    mainDataLiat:[],
    pname:'',
    cname:'',
 })



 const handleSearch = () => {
    axios({
        url:'http://hmajax.itheima.net/api/area',
        params: {
            pname: state.pname || '',
            cname: state.cname || ''
        }
    }).then(res => {
        console.log(res);
        state.mainDataLiat = res.data.list
    })
 }
 
 </script>
 

常用请求方法

get
post
注意点:属性写params,会将数据拼接在url后,以?key=value&key=value的形式;写data,则会以json或者其他格式传输

    axios({
        url:'http://hmajax.itheima.net/api/register',
        method: 'post', // 如果是get 可以不写
        data: {
            // username: state.username || '',
            username: 'itheima007',
            password: state.password || ''
        }
    }).then(res => {
        console.log(res);
        // state.mainDataLiat = res.data.list
    })

获取错误信息

    axios({
        url:'http://hmajax.itheima.net/api/register',
        // method: 'post',
        data: {
            // username: state.username || '',
            username: 'itheima007',
            password: state.password || ''
        }
    }).then(res => {
        console.log(res);
        // state.mainDataLiat = res.data.list
    }).catch(err => {
        ElMessage.error(err.response.data.message)
    })

上传图片/文件

格式为form-data

HTTP协议

请求报文

GET /api/register?username=itheima007&password= HTTP/1.1
Accept: application/json, text/plain, */*
Accept-Encoding: gzip, deflate
Accept-Language: zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6
Connection: keep-alive
Host: hmajax.itheima.net
Origin: http://localhost:5173
Referer: http://localhost:5173/
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36 Edg/124.0.0.0

{"username":"itheima007","password":"22222"}

响应报文

XMLHttpRequest

查询参数

<template>
    <div class="flex">
        <span>省:</span>
        <el-input v-model="state.pname" style="width: 200px;"></el-input>
    </div>
    <div class="flex">
        <span>市:</span>
        <el-input v-model="state.cname" style="width: 200px;"></el-input>
    </div>
    <el-button @click="handleSearch" type="primary">查询</el-button>
    <h5 v-for="item in state.mainDataLiat">{{ item }}</h5>

 </template>
 
 <script setup name="Model" lang="ts">
 import { reactive } from 'vue'
 import axios from 'axios';
import { stat } from 'fs';

 let state = reactive({
    mainDataLiat:[],
    pname:'',
    cname:'',
 })



 const handleSearch = () => {
    // axios({
    //     url:'http://hmajax.itheima.net/api/area',
    //     params: {
    //         pname: state.pname || '',
    //         cname: state.cname || ''
    //     }
    // }).then(res => {
    //     console.log(res);
    //     state.mainDataLiat = res.data.list
    // })
    const xml = new XMLHttpRequest()
    xml.open('GET',`http://hmajax.itheima.net/api/area?pname=${state.pname}&cname=${state.cname}`)
    xml.addEventListener('loadend',()=>{
        state.mainDataLiat = JSON.parse(xml.response).list
        console.log(state.mainDataLiat);

    })
    xml.send()
 }
 
 </script>
 

json参数

<template>
    <div class="flex">
        <span>账号:</span>
        <el-input v-model="user.username" style="width: 200px;"></el-input>
    </div>
    <div class="flex">
        <span>密码:</span>
        <el-input type="password" v-model="user.password" style="width: 200px;"></el-input>
    </div>
    <el-button @click="handleReg" type="primary">注册</el-button>

 </template>
 
 <script setup name="Model" lang="ts">
 import { reactive } from 'vue'
 import axios from 'axios';
import { stat } from 'fs';
import { ElMessage } from 'element-plus';

let user = reactive({
    username: '',
    password: ''
})


 const handleReg = () => {
    // axios({
    //     url:'http://hmajax.itheima.net/api/area',
    //     params: {
    //         pname: state.pname || '',
    //         cname: state.cname || ''
    //     }
    // }).then(res => {
    //     console.log(res);
    //     state.mainDataLiat = res.data.list
    // })
    const xml = new XMLHttpRequest()
    xml.open('POST',`http://hmajax.itheima.net/api/register`)
    xml.setRequestHeader('Content-type', 'application/json')
    const userStr = JSON.stringify(user)
    xml.addEventListener('loadend',()=>{
        console.log(JSON.parse(xml.response).message);
        ElMessage.success(JSON.parse(xml.response).message)
    })
    xml.send(userStr)
 }
 
 </script>
 

Promise

 // 使用Promise管理异步任务
 const p = new Promise((resolve, reject) => {
    setTimeout(() => {
        console.log('hhhhhhhhhhhhhh');
        
        // resolve('模拟成功请求')
        reject(new Error('模拟失败请求'))
    }, 2000);
}).then(res => {
    console.log(res);
}).catch(err => {
    console.log(err);
})

三种状态

pending
fulfilled
rejected

XMLHttpRequest结合Promise

<template>
    <div class="flex">
        <span>账号:</span>
        <el-input v-model="user.username" style="width: 200px;"></el-input>
    </div>
    <div class="flex">
        <span>密码:</span>
        <el-input type="password" v-model="user.password" style="width: 200px;"></el-input>
    </div>
    <el-button @click="handleReg" type="primary">注册</el-button>

 </template>
 
 <script setup name="Model" lang="ts">
 import { reactive } from 'vue'
 import axios from 'axios';
import { stat } from 'fs';
import { ElMessage } from 'element-plus';
import { resolve } from 'path';
import { error, log } from 'console';

let user = reactive({
    username: '',
    password: ''
})


 const handleReg = () => {
    // axios({
    //     url:'http://hmajax.itheima.net/api/area',
    //     params: {
    //         pname: state.pname || '',
    //         cname: state.cname || ''
    //     }
    // }).then(res => {
    //     console.log(res);
    //     state.mainDataLiat = res.data.list
    // })
    
    const p = new Promise((resolve, reject) => {
        const xml = new XMLHttpRequest()
        xml.open('POST',`http://hmajax.itheima.net/api/register`)
        xml.setRequestHeader('Content-type', 'application/json')
        const userStr = JSON.stringify(user)
        xml.addEventListener('loadend',()=>{
            // console.log(JSON.parse(xml.response).message);
            // ElMessage.success(JSON.parse(xml.response).message)
            if(xml.status >= 200 && xml.status < 300) {
                resolve(JSON.parse(xml.response))
            } else {
                reject(new Error(xml.response))
            }
        })
        xml.send(userStr)
    }).then(res => {
        ElMessage.success(res.message)
    }).catch(err => {
        ElMessage.error(err.message)
    })
 
 }

封装成函数

<template>
    <div class="flex">
        <span>账号:</span>
        <el-input v-model="user.username" style="width: 200px;"></el-input>
    </div>
    <div class="flex">
        <span>密码:</span>
        <el-input type="password" v-model="user.password" style="width: 200px;"></el-input>
    </div>
    <el-button @click="handleReg" type="primary">注册</el-button>

 </template>
 
 <script setup name="Model" lang="ts">
 import { reactive } from 'vue'
 import axios from 'axios';
import { stat } from 'fs';
import { ElMessage } from 'element-plus';
import { resolve } from 'path';
import { error, log } from 'console';
import { rejects } from 'assert';

let user = reactive({
    username: '',
    password: ''
})


 const handleReg = () => {
    // axios({
    //     url:'http://hmajax.itheima.net/api/area',
    //     params: {
    //         pname: state.pname || '',
    //         cname: state.cname || ''
    //     }
    // }).then(res => {
    //     console.log(res);
    //     state.mainDataLiat = res.data.list
    // })
    
    // const p = new Promise((resolve, reject) => {
    //     const xml = new XMLHttpRequest()
    //     xml.open('POST',`http://hmajax.itheima.net/api/register`)
    //     xml.setRequestHeader('Content-type', 'application/json')
    //     const userStr = JSON.stringify(user)
    //     xml.addEventListener('loadend',()=>{
    //         // console.log(JSON.parse(xml.response).message);
    //         // ElMessage.success(JSON.parse(xml.response).message)
    //         if(xml.status >= 200 && xml.status < 300) {
    //             resolve(JSON.parse(xml.response))
    //         } else {
    //             reject(new Error(xml.response))
    //         }
    //     })
    //     xml.send(userStr)
    // }).then(res => {
    //     ElMessage.success(res.message)
    // }).catch(err => {
    //     ElMessage.error(err.message)
    // })
    
    myAxios({
        method: 'POST',
        url: 'http://hmajax.itheima.net/api/register',
        data: user,
    }).then(res => {
        ElMessage.success(res.message)
    }).catch(err => {
        ElMessage.error(err.message)
    })
 }

 function myAxios(config) {
    return new Promise((resolve, reject) => {
        const xml = new XMLHttpRequest()
        xml.open(config.method || 'GET', config.url)
        xml.addEventListener('loadend', ()=> {
            if(xml.status >= 200 && xml.status < 300) {
                resolve(JSON.parse(xml.response))
            } else {
                reject(new Error(xml.response))
            }
        })
        if(config.data) {
            xml.setRequestHeader('Content-type', 'application/json')
            const jsonStr = JSON.stringify(config.data)
            xml.send(jsonStr)
        } else {
            xml.send()
        }
        
    })
 }


 </script>

回调地狱、用Promise解决回调地狱


用Promise解决回调地狱

 function fetchData() {  
  return new Promise((resolve, reject) => {  
    // 假设这是一个异步操作,比如从服务器获取数据  
    setTimeout(() => {  
      resolve('Data from first Promise');  
    }, 1000);  
  });  
}  
  
function processData(data) {  
  return new Promise((resolve, reject) => {  
    // 假设这是一个处理数据的异步操作  
    setTimeout(() => {  
      const processedData = `Processed ${data}`;  
      reject(new Error(processedData));  
    }, 1000);  
  });  
}  
  
// 链式调用 Promise  
fetchData()  
  .then(data => {  
    console.log(data); // 输出: Data from first Promise  
    return processData(data); // 返回一个新的 Promise  
  })  
  .then(processedData => {  
    console.log(processedData); // 输出: Processed Data from first Promise  
  })  
  .catch(error => {  
    console.error('An error occurred:', error);  
  });

回调地狱 用async await解决

async function getData() {
    try {
        const pObj = await axios({url: 'http://hmajax.itheima.net/api/province'})
        console.log(pObj)
        const pname = pObj.data.list[0]
        const cObj = await axios({url: 'http://hmajax.itheima.net/api/city', params: {pname}})
        const cname = cObj.data.list[0]
        const aObj = await axios({url: 'http://hmajax.itheima.net/api/area', params: {pname, cname}})
        console.log(pname, cname, aObj);
    } catch(err) {
        console.dir(err)
    }
}
getData()

事件循环

微任务与宏任务


const promiseAll = Promise.all([promise1,promise2,promise3,promise4])

合并多个promise对象,等待同时成功或有部分失败后再做后续处理

<template>
    <el-table :data="tableData" @change="console.log('changed',tableData);">
        <el-table-column prop="area" label="area"></el-table-column>
        <el-table-column prop="date" label="date"></el-table-column>
        <el-table-column prop="dayForecast" label="dayForecast"></el-table-column>
    </el-table>

</template>

<script setup name="Model" lang="ts">
import axios from 'axios';
import { reactive } from 'vue';
const tableData = reactive([])
async function getData() {
    try {
        const promise1 = await axios({url: 'http://hmajax.itheima.net/api/weather', params: {city: '110100'}})
        // tableData.push({
        //     area: promise1.data.data.area,
        //     date: promise1.data.data.date,
        //     dayForecast: promise1.data.data.dayForecast[0].weather,
        // })       
        const promise2 = await axios({url: 'http://hmajax.itheima.net/api/weather', params: {city: '310100'}})
        // tableData.push({
        //     area: promise2.data.data.area,
        //     date: promise2.data.data.date,
        //     dayForecast: promise2.data.data.dayForecast[0].weather,
        // })
        const promise3 = await axios({url: 'http://hmajax.itheima.net/api/weather', params: {city: '440100'}})
        // tableData.push({
        //     area: promise3.data.data.area,
        //     date: promise3.data.data.date,
        //     dayForecast: promise3.data.data.dayForecast[0].weather,
        // })
        const promise4 = await axios({url: 'http://hmajax.itheima.net/api/weather', params: {city: '440300'}})
        // tableData.push({
        //     area: promise4.data.data.area,
        //     date: promise4.data.data.date,
        //     dayForecast: promise4.data.data.dayForecast[0].weather,
        // })
        console.log(tableData);
        const promiseAll = Promise.all([promise1,promise2,promise3,promise4])
        console.log('promiseAll,promiseAll',promiseAll);

        promiseAll.then(res => {
            console.log(res);
            
            tableData.push({
                area: res[0].data.data.area,
                date: res[0].data.data.date,
                dayForecast: res[0].data.data.dayForecast[0].weather,
            })
            tableData.push({
                area: res[1].data.data.area,
                date: res[1].data.data.date,
                dayForecast: res[1].data.data.dayForecast[0].weather,
            })
            tableData.push({
                area: res[2].data.data.area,
                date: res[2].data.data.date,
                dayForecast: res[2].data.data.dayForecast[0].weather,
            })
            tableData.push({
                area: res[3].data.data.area,
                date: res[3].data.data.date,
                dayForecast: res[3].data.data.dayForecast[0].weather,
            })
        })
    } catch(err) {
        console.dir(err)
    }
}

getData()

console.log('aaa',tableData);

</script>

标签:xml,const,state,res,Ajax,001,console,data,视频教程
From: https://www.cnblogs.com/ayubene/p/18185350

相关文章

  • CSP历年复赛题-P1049 [NOIP2001 普及组] 装箱问题
    原题链接:https://www.luogu.com.cn/problem/P1049题意解读:装尽可能多的物品,使得总体积越大越好,即剩余空间最小,还是一个01背包问题,物品的体积就是其价值。解题思路:01背包模版题,物品体积、价值相同,直接采用一维dp。100分代码:#include<bits/stdc++.h>usingnamespacestd;co......
  • CSP历年复赛题-P1030 [NOIP2001 普及组] 求先序排列
    原题链接:https://www.luogu.com.cn/problem/P1030题意解读:已知中序、后序,求先序。解题思路:与洛谷题单指南-二叉树-P1827[USACO3.4]美国血统AmericanHeritage非常类似,不在介绍过程,直接给出代码。100分代码:#include<bits/stdc++.h>usingnamespacestd;stringin,post......
  • CSP历年复赛题-P1028 [NOIP2001 普及组] 数的计算
    原题链接:https://www.luogu.com.cn/problem/P1028题意解读:给定n,构造数列,可以用递归或者递推。解题思路:1、递归定义count(n)返回数列的个数  n==1时,count(n)=1  n!=1时,count(n)=1+count(1)+count(2)+...+count(n/2)注意,递归会导致大量重复计算,需要用一个hash......
  • CSP历年复赛题-P1029 [NOIP2001 普及组] 最大公约数和最小公倍数问题
    原题链接:https://www.luogu.com.cn/problem/P1029题意解读:已知x,y,求有多少对p、q,使得p、q的最大公约数为x,最小公倍数为y。解题思路:枚举法即可。枚举的对象:枚举p,且p必须是x的倍数,还有p<=yq的计算:q=x*y/p,q要存在,必须x*y%p==0,且gcd(p,q)==x100分代码:#include......
  • P5782 [POI2001] 和平委员会
    P5782[POI2001]和平委员会题目链接思路:因为\(u\)和\(v\)矛盾,即\(\lnot(u\landv)\)。转化成\(\lnotu\lor\lnotv\)。那么根据\(2-SAT\)标准处理方式。转化为:\((u\rightarrow\lnotv)\land(v\rightarrow\lnotu)\)。这里有个小技巧:我们将下标-1,这样我......
  • 03--JQuery、Ajax
    jQuery与AjaxjQuery是一个曾经火遍大江南北的一个Javascript的第三方库jQuery的理念:writelessdomore.其含义就是让前端程序员从繁琐的js代码中解脱出来.我们来看看是否真的能解脱出来jQuery的版本:jQuery一共提出过3个大版本.分别是1.x,2.x和3.x.注意:虽然目前最新的......
  • [NOIP2001 提高组] 数的划分
    个人博客传送锚点:https://www.acwing.com/blog/content/55495/传送锚点:https://www.luogu.com.cn/problem/P1025题目描述将整数$n$分成$k$份,且每份不能为空,任意两个方案不相同(不考虑顺序)。例如:$n=7$,$k=3$,下面三种分法被认为是相同的。$1,1,5$;$1,5,1$;$5,1,1$.问有多......
  • 解决ajax请求参数过多导致参数被截断的问题
    最近发现了个问题:ajaxpost请求查询参数数量动态变化有200-250000个,当参数超过一定数量N时,post传到后台接的参数就只有N个,多出的参数都没附到请求中,这也是奇怪的事情,浏览器对参数的个数有限制。jsconstpayload={date:"2024-05-10",sn:[]};for(leti=1;i<1000......
  • 【编译器001-001】总览
    参考资料BuildingaCompiler国内搬运[中英字幕]C#构建编译器(BuildingaCompiler)代码地址:https://github.com/terrajobst/minsk具体思路这个作者使用的是dotnet,而我对dotnet不怎么感冒,所以我的方式是先使用dotnet跟着抄一遍,然后使用自己喜欢的语言写一......
  • Ajax
    Ajax笔记1.Ajax简介AJAX即“AsynchronousJavascriptAndXML”(异步JavaScript和XML)。AJAX不是一种新的编程语言,而是一种使用现有标准的新方法。它是一种用于从网页访问Web服务器的技术。AJAX允许您在不重新加载页面的情况下向服务器发出请求。AJAX可以与服务器通信,交......