在前端頁面中使用 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>