一、使用xhr和promise获取省份列表
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div class="test"></div>
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
<script>
const p = new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest()
xhr.open("GET", "https://hmajax.itheima.net/api/province")
xhr.addEventListener('loadend', () => {
// console.log(xhr.response)
// console.log(xhr)
if (xhr.status >= 200 && xhr.status < 300) {//状态码,200代表成功,404代表错误
resolve(JSON.parse(xhr.response))
} else {
reject(new Error(xhr.response))
}
})
xhr.send()
})
p.then((result) => {
console.log(result)
document.querySelector(".test").innerHTML = result.list.join('<br>')//将请求到的数据渲染到页面上
}).catch((error) => {
console.log(error)
document.querySelector('.test').innerHTML = error.message
})
</script>
</body>
</html>
二、使用axios,根据省份和城市查询地区
效果如下
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
省份<input type="text" class="ipt1">
城市<input type="text" class="ipt2">
<button class="btn">查询</button>
<div class="test"></div>
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
<script>
document.querySelector(".btn").addEventListener("click", () => {
const pname = document.querySelector('.ipt1').value
const cname = document.querySelector('.ipt2').value
axios({
url: 'https://hmajax.itheima.net/api/area',
params: {
pname: pname,
cname: cname
}
}).then((result) => {
console.log(result)
document.querySelector('.test').innerHTML = result.data.list.join("<br>")
})
})
</script>
</body>
</html>