在前端页面中使用 axios 时,需要获得返回值,进行后续的操作。
问题描述
如下,返回 isBol 的值,这样写只能返回 空
<div id="app">
<input type="button" value="get请求" id="get" />
<input type="button" value="post请求" id="post" />
<input type="button" value="post请求2" id="post2" />
</div>
<!-- 开发环境版本,包含了有帮助的命令行警告 -->
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script>
function login() {
let isBol = ""
axios.post("http://localhost:8080//final01_war_exploded/users/actions/login", {username:"100001", password:"123456"})
.then(function(response) {
console.log(response)
isBol = true
}, function(err){
console.log(err)
isBol = false
})
return isBol
}
/*
post请求
*/
document.querySelector("#post2").onclick = function(){
if(login()) {
console.log("shaqk")
location = "vue计数器.html"
}
}
</script>
分析原因
axios请求是异步的 ,需要使用async/await
解决方法
在函数名前添加 async
且在 axios 前添加 await
。
<script>
async function login() {
let isBol = ""
await axios.post("http://localhost:8080//final01_war_exploded/users/actions/login", {username:"100001", password:"123456"})
.then(function(response) {
console.log(response)
isBol = true
}, function(err){
console.log(err)
isBol = false
})
return isBol
}
</script>