查询参数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