先看看页面。
出示二维码:
扫码登录成功后自动切换。
一、需要用到的库
本实例使用vue,二维码生成使用jquery-qrcode.js
二、index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>扫码登录</title>
<script src="../js/jquery.min.js"></script>
<script src="../js/vue/vue.min.js"></script>
<script src="../js/vue/vue-resource.min.js"></script>
<script src="../js/jquery-qrcode.js"></script>
<style>
.main-box {
width: 200px;
height: 200px;
margin: auto;
}
.btn-show {
margin-top: 40px;
}
canvas {
margin-top: 40px;
}
</style>
</head>
<body>
<div id="app">
<div class="main-box">
<div id="output"></div>
<h3>{{ info }}</h3>
<button class="btn-show" @click="getScanCode()">显示二维码</button>
</div>
</div>
</body>
<script src="../js/index.js"></script>
</html>
三、index.js
new Vue({
el: '#app',
data: {
code: '',
info: '',
t1: null,
t2: null,
state: 0
},
methods: {
//获取扫描识别码
getScanCode() {
this.$http.get('http://192.168.0.100:7021/api/user/getScanCode')
.then(
function (response) {
var that = this;
//响应成功回调
that.code = response.data.code
//清空二维码画布 否则会保留原来的
//$('#output').children('*').remove();
$('#output').empty();
$('#output').qrcode(this.code);
//在此轮询 1秒一次
this.loopAsk()
},
function (response) {
//响应错误回调
alert('有错误')
}
);
},
//轮询
loopAsk() {
var that = this
that.t1 = setInterval(function () {
that.t2 = setTimeout(function () {
//console.log('this.state')
that.askLoginInfo()
}, 1000)
}, 1000)
},
//查询登录信息
askLoginInfo() {
console.log('askLoginInfo')
this.$http.get('http://192.168.0.100:7021/api/user/askLogin', {params: {code: this.code}})
.then(
function (response) {
var name = response.data.username
console.log(name)
if (name == null) {
console.log('unkown')
} else {
var i = name + " 成功登录"
console.log(i)
this.info = i
clearInterval(this.t1)
clearInterval(this.t2)
$('#output').empty();
}
},
function (response) {
alert('有错误')
}
);
}
}
});