// pages/my/my.js var app = getApp(); Page({ data: { buttonText: '发送验证码', phone: "", code: "", countDown: 60, timer: null, sendCodeDisabled: false, }, onPhoneInput: function(e) { this.setData({ phone: e.detail }); }, onCodeInput: function(e) { this.setData({ code: e.detail }); }, sendCode: function() { if (this.data.sendCodeDisabled) return; // 手机号验证 if (this.data.phone.length < 11) { wx.showToast({ title: '手机号长度错误', icon: "none", }); return; } var reg = /^(1[3|4|5|6|7|8|9])\d{9}$/; if (!reg.test(this.data.phone)) { wx.showToast({ title: '手机号格式错误', icon: "none", }); return; } wx.request({ url: 'http://127.0.0.1:8000/api/message/', data: { phone: this.data.phone }, method: 'GET', success: (res) => { if (res.data.status) { this.setData({ sendCodeDisabled: true, timer: setInterval(this.countDown.bind(this), 1000) }); wx.showToast({ title: '验证码发送成功', icon: "none", }); } else { wx.showToast({ title: (res.data && res.data.message) || '验证码发送失败', icon: "none", }); } }, fail: (err) => { wx.showToast({ title: '网络错误,请重试', icon: 'none' }); } }); }, countDown: function() { var countDown = this.data.countDown - 1; if (countDown <= 0) { clearInterval(this.data.timer); this.setData({ buttonText: '发送验证码', sendCodeDisabled: false, countDown: 60 }); return; } this.setData({ buttonText: countDown + 's', countDown: countDown }); }, login: function() { if (!this.data.phone || !this.data.code) { wx.showToast({ title: '请输入手机号和验证码', icon: 'none' }); return; } wx.request({ url: 'http://127.0.0.1:8000/api/login/', method: 'POST', header: { 'Content-Type': 'application/json' }, data: { phone: this.data.phone, code: this.data.code }, success: (res) => { if (res.data && res.data.status) { // 强化token存储逻辑 try { const token = res.data.data.token; const userInfo = res.data.data; wx.setStorageSync('token', token); wx.setStorageSync('userInfo', userInfo); // 验证存储是否成功 const storedToken = wx.getStorageSync('token'); if (!storedToken) { throw new Error('Token存储失败'); } app.globalData.userInfo = userInfo; app.globalData.token = token; wx.showToast({ title: '登录成功', icon: 'success' }); // 跳转前检查页面栈 const pages = getCurrentPages(); if (pages.length > 1) { wx.navigateBack(); } else { wx.switchTab({ url: '/pages/my/my' }); } } catch (e) { console.error('登录处理错误:', e); wx.showToast({ title: '登录状态保存失败', icon: 'none' }); } } else { wx.showToast({ title: (res.data && res.data.message) || '登录失败', icon: 'none' }); } }, fail: (err) => { wx.showToast({ title: '网络错误,请重试', icon: 'none' }); } }); }, onUnload: function() { if (this.data.timer) { clearInterval(this.data.timer); } } });