给我用js写一个通过文字生成二维码并且弹窗到页面居中显示而且下方加入倒计时30分钟并向musecloudtechgetstatus轮询查询当前支付状态
以下是一个实现上述要求的JS代码:
// 引入 QRCode.js 库
import QRCode from 'qrcode';
// 获取页面中的元素
const qrcodeModal = document.getElementById('qrcode-modal');
const qrcodeImg = document.getElementById('qrcode-img');
const countdown = document.getElementById('countdown');
// 定义倒计时时间
const countDownTime = 30 * 60 * 1000;
// 定义生成二维码函数
function generateQRCode(text) {
// 生成二维码图片
QRCode.toDataURL(text, (err, url) => {
if (err) {
console.error(err);
return;
}
// 将二维码图片添加到模态框中
qrcodeImg.src = url;
// 显示模态框
qrcodeModal.style.display = 'block';
// 开始倒计时
startCountDown();
});
}
// 定义倒计时函数
let timer = null;
function startCountDown() {
let remainingTime = countDownTime;
// 更新倒计时显示
countdown.innerText = formatTime(remainingTime);
// 向服务器查询支付状态
checkPaymentStatus();
// 开始倒计时
timer = setInterval(() => {
remainingTime -= 1000;
if (remainingTime <= 0) {
// 倒计时结束,关闭模态框
clearInterval(timer);
qrcodeModal.style.display = 'none';
} else {
// 更新倒计时显示
countdown.innerText = formatTime(remainingTime);
// 向服务器查询支付状态
checkPaymentStatus();
}
}, 1000);
}
// 定义格式化时间函数
function formatTime(time) {
const minutes = Math.floor(time / 60000);
const seconds = Math.floor((time % 60000) / 1000);
return `${minutes}:${seconds.toString().padStart(2, '0')}`;
}
// 定义查询支付状态函数
async function checkPaymentStatus() {
const response = await fetch('https://musecloud.tech/getstatus');
const json = await response.json();
if (json.status === 'paid') {
// 支付成功,关闭模态框
clearInterval(timer);
qrcodeModal.style.display = 'none';
}
}
// 调用生成二维码函数
generateQRCode('Hello, world!');
在上述代码中,我们使用了 QRCode.js 库来生成二维码图片。在生成二维码时,我们使用了 toDataURL 方法将二维码图片转换为 Base64 编码的字符串,并将其显示在页面中的 img 元素中。
在显示二维码图片时,我们将其添加到一个模态框中,并在模态框中添加了一个倒计时显示,用于提示用户剩余支付时间。倒计时结束后,我们关闭模态框。
在倒计时过程中,我们使用了 setInterval 方法来更新倒计时显示和向服务器查询支付状态。查询支付状态的过程中,我们使用了 fetch 方法和 await 关键字来实现异步请求。如果支付状态为 paid,我们将关闭模态框。
需要注意的是,为了使代码更加简洁和易读,我们省略了部分与页面元素相关的代码。如果需要完整的代码,请参考下面的代码片段
原文地址: https://www.cveoy.top/t/topic/frPV 著作权归作者所有。请勿转载和采集!