案例分析: 如圖所示,頁面載入時有數據回填,同時實現select表單同步和圖片上傳,保存後上傳至伺服器等功能 HTML模板: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA ...
案例分析:
如圖所示,頁面載入時有數據回填,同時實現select表單同步和圖片上傳,保存後上傳至伺服器等功能
HTML模板:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>08.案例_個人信息修改</title>
<link rel="stylesheet" href="https://unpkg.com/[email protected]/dist/css/bootstrap.min.css" />
<style>
.form-select {
width: 103px;
display: inline-block;
}
.col-form-label {
text-align: right;
}
.figure-img {
width: 100px;
height: 100px;
cursor: pointer;
}
#upload {
display: none;
}
</style>
</head>
<body>
<div class="container">
<h1 class="p-5">個人設置</h1>
<form class="col-6">
<div class="row mb-3">
<label class="col-form-label col-3">昵稱:</label>
<div class="col-9">
<input class="form-control col-9" type="text" name="nickname" />
</div>
</div>
<div class="row mb-3">
<label class="col-form-label col-3">籍貫:</label>
<div class="col-9">
<select class="form-select col-4" name="province">
<option value="">--省--</option>
</select>
<select class="form-select col-4" name="city">
<option value="">--市--</option>
</select>
<select class="form-select col-4" name="area">
<option value="">--區--</option>
</select>
</div>
</div>
<div class="row mb-3">
<label class="col-form-label col-3">頭像:</label>
<div class="col-9">
<input class="form-control col-9" type="hidden" name="avatar" />
<figure class="figure">
<input type="file" id="upload" />
<img src="https://yanxuan-item.nosdn.127.net/12a882699bd531a1bd428bffe1989525.jpg"
class="figure-img img-fluid rounded" alt="..." />
<figcaption class="figure-caption">修改頭像</figcaption>
</figure>
</div>
</div>
<div class="row mb-3">
<label class="col-3"></label>
<div class="col-9">
<button class="btn btn-primary">保存</button>
</div>
</div>
</form>
</div>
<script src="https://unpkg.com/[email protected]/dist/js/bootstrap.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/axios.min.js"></script>
<script src="./lib/form-serialize.js"></script>
</body>
</html>
一.頁面回填
通過獲取內置個人信息進行頁面回填
<script>
// 首碼基地址
axios.defaults.baseURL = 'http://ajax-api.itheima.net/'
// 獲取標簽方法$
function $(id) {
return document.querySelector('#' + id)
}
// 數據回填方法
async function getInfo() {
const res = await axios.get('api/settings')
const { nickname, province, city, area, avatar } = res.data.data
// 昵稱
$('nickname').value = nickname
// 頭像地址
$('avatar').src = avatar
// 給頭像框input進行賦值,方便後期拿取數據
$('avatarInp').value = avatar
// 省數據
const provinceAll = await axios.get('api/province')
$('province').innerHTML += provinceAll.data.data.map(item => `<option value="${item}">${item}</option>`).join('')
$('province').value = province
// 市數據
const cityAll = await axios.get('api/city?pname=' + province)
$('city').innerHTML += cityAll.data.data.map(item => `<option value="${item}">${item}</option>`).join('')
$('city').value = city
// 區數據
const areaAll = await axios.get(`api/area?pname=${province}&cname=${city}`)
$('area').innerHTML += areaAll.data.data.map(item => `<option value="${item}">${item}</option>`).join('')
$('area').value = area
}
// 調用回填方法
getInfo()
</script>
二.省市區下拉框的聯動
<script>
// 省數據下拉框
$('province').addEventListener('change', async () => {
// 獲取省下市數據
const cityAll = await axios.get('api/city?pname=' + $('province').value)
// 渲染市數據
$('city').innerHTML = cityAll.data.data.map(item => `<option value="${item}">${item}</option>`).join('')
// 獲取市下區數據
const areaAll = await axios.get(`api/area?pname=${$('province').value}&cname=${$('city').value}`)
// 渲染區數據
$('area').innerHTML = areaAll.data.data.map(item => `<option value="${item}">${item}</option>`).join('')
})
$('city').addEventListener('change', async () => {
const areaAll = await axios.get(`api/area?pname=${$('province').value}&cname=${$('city').value}`)
$('area').innerHTML = areaAll.data.data.map(item => `<option value="${item}">${item}</option>`).join('')
})
</script>
三.頭像圖片上傳功能
<script>
// 圖片上傳功能
$('upload').addEventListener('change', (e) => {
// 非空判斷
if (e.target.files.length === 0) {
return
}
// 創建FormData接收
const fd = new FormData()
// 將圖片數據添加到fd中
fd.append('avatar', e.target.files[0])
// 圖片上傳介面
axios.post('api/file', fd).then(res => {
console.log(res);
$('avatar').src = res.data.data.url
// 給頭像框input進行賦值,方便拿取數據
$('avatarInp').value = res.data.data.url
})
})
// 圖片點擊事件
$('avatar').addEventListener('click', () => {
// 優化圖片上傳功能
$('upload').click()
})
</script>
四.將數據上傳至伺服器保存
<script>
// 上傳點擊事件
$('uploadAll').addEventListener('click', async (e) => {
// 取消預設刷新操作
e.preventDefault()
// 用serialize獲取表單中所有內容(前面給頭像框input賦值的應用)
const userFormall = serialize($('userForm'), { hash: true })
try {
// 執行成功,上傳數據並彈出ok彈框
await axios.put('api/settings', userFormall)
alert('ok')
} catch (error) {
alert('error')
}
})
</script>
五.個人經驗
①省市區下拉框聯動時,操作省數據聯動市數據時,仍需對區數據進行聯動
②給圖片input框的value賦值,方便最後上傳伺服器時用serialize獲取數據
③附完整源碼
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>08.案例_個人信息修改</title>
<link rel="stylesheet" href="https://unpkg.com/[email protected]/dist/css/bootstrap.min.css" />
<style>
.form-select {
width: 103px;
display: inline-block;
}
.col-form-label {
text-align: right;
}
.figure-img {
width: 100px;
height: 100px;
cursor: pointer;
}
#upload {
display: none;
}
</style>
</head>
<body>
<div class="container">
<h1 class="p-5">個人設置</h1>
<form class="col-6" id="userForm">
<div class="row mb-3">
<label class="col-form-label col-3">昵稱:</label>
<div class="col-9">
<input class="form-control col-9" type="text" name="nickname" id="nickname" />
</div>
</div>
<div class="row mb-3">
<label class="col-form-label col-3">籍貫:</label>
<div class="col-9">
<select class="form-select col-4" name="province" id="province">
<option value="">--省--</option>
</select>
<select class="form-select col-4" name="city" id="city">
<option value="">--市--</option>
</select>
<select class="form-select col-4" name="area" id="area">
<option value="">--區--</option>
</select>
</div>
</div>
<div class="row mb-3">
<label class="col-form-label col-3">頭像:</label>
<div class="col-9">
<input class="form-control col-9" type="hidden" name="avatar" id="avatarInp" />
<figure class="figure">
<input type="file" id="upload" />
<img src="https://yanxuan-item.nosdn.127.net/12a882699bd531a1bd428bffe1989525.jpg"
class="figure-img img-fluid rounded" alt="..." id="avatar" />
<figcaption class="figure-caption" id="load">修改頭像</figcaption>
</figure>
</div>
</div>
<div class="row mb-3">
<label class="col-3"></label>
<div class="col-9">
<button class="btn btn-primary" id="uploadAll">保存</button>
</div>
</div>
</form>
</div>
<script src="https://unpkg.com/[email protected]/dist/js/bootstrap.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/axios.min.js"></script>
<script src="./lib/form-serialize.js"></script>
<script>
// 首碼基地址
axios.defaults.baseURL = 'http://ajax-api.itheima.net/'
// 獲取標簽方法$
function $(id) {
return document.querySelector('#' + id)
}
// 數據回填方法
async function getInfo() {
const res = await axios.get('api/settings')
const { nickname, province, city, area, avatar } = res.data.data
// 昵稱
$('nickname').value = nickname
// 頭像地址
$('avatar').src = avatar
// 給頭像框input進行賦值,方便後期拿取數據
$('avatarInp').value = avatar
// 省數據
const provinceAll = await axios.get('api/province')
$('province').innerHTML += provinceAll.data.data.map(item => `<option value="${item}">${item}</option>`).join('')
$('province').value = province
// 市數據
const cityAll = await axios.get('api/city?pname=' + province)
$('city').innerHTML += cityAll.data.data.map(item => `<option value="${item}">${item}</option>`).join('')
$('city').value = city
// 區數據
const areaAll = await axios.get(`api/area?pname=${province}&cname=${city}`)
$('area').innerHTML += areaAll.data.data.map(item => `<option value="${item}">${item}</option>`).join('')
$('area').value = area
}
// 調用回填方法
getInfo()
// 省數據下拉框
$('province').addEventListener('change', async () => {
// 獲取省下市數據
const cityAll = await axios.get('api/city?pname=' + $('province').value)
// 渲染市數據
$('city').innerHTML = cityAll.data.data.map(item => `<option value="${item}">${item}</option>`).join('')
// 獲取市下區數據
const areaAll = await axios.get(`api/area?pname=${$('province').value}&cname=${$('city').value}`)
// 渲染區數據
$('area').innerHTML = areaAll.data.data.map(item => `<option value="${item}">${item}</option>`).join('')
})
$('city').addEventListener('change', async () => {
const areaAll = await axios.get(`api/area?pname=${$('province').value}&cname=${$('city').value}`)
$('area').innerHTML = areaAll.data.data.map(item => `<option value="${item}">${item}</option>`).join('')
})
// 圖片上傳功能
$('upload').addEventListener('change',(e)=>{
// 非空判斷
if(e.target.files.length===0){
return
}
// 創建FormData接收
const fd = new FormData()
// 將圖片數據添加到fd中
fd.append('avatar', e.target.files[0])
// 圖片上傳介面
axios.post('api/file',fd).then(res=>{
console.log(res);
$('avatar').src = res.data.data.url
// 給頭像框input進行賦值,方便拿取數據
$('avatarInp').value = res.data.data.url
})
})
// 圖片點擊事件
$('avatar').addEventListener('click',()=>{
// 優化圖片上傳功能
$('upload').click()
})
// 上傳點擊事件
$('uploadAll').addEventListener('click', async (e)=>{
// 取消預設刷新操作
e.preventDefault()
// 用serialize獲取表單中所有內容(前面給頭像框input賦值的應用)
const userFormall = serialize($('userForm'),{hash:true})
try {
// 執行成功,上傳數據並彈出ok彈框
await axios.put('api/settings',userFormall)
alert('ok')
} catch (error) {
alert('error')
}
})
</script>
</body>
</html>
本文來自博客園,作者:三井綾子,轉載請註明原文鏈接:https://www.cnblogs.com/Ayako/p/16900651.html