// pages/threshold/threshold.js Page({ data: { threshold: null, // 初始化为null newThreshold: null, loading: true // 添加加载状态 }, onLoad() { this.getThreshold(); }, // 获取当前阈值(优化版) getThreshold() { this.setData({ loading: true }); wx.request({ url: 'https://soilgd.com:5000/get-threshold', success: (res) => { if (res.statusCode === 200 && res.data && typeof res.data.current_threshold === 'number') { this.setData({ threshold: res.data.current_threshold, }); } else { wx.showToast({ title: '数据格式错误', icon: 'error' }); console.error('Invalid response:', res); } }, fail: (err) => { wx.showToast({ title: '请求失败', icon: 'error' }); console.error('API Error:', err); }, complete: () => { this.setData({ loading: false }); } }); }, // 输入框改变事件(添加校验) onInput(e) { const value = Number(e.detail.value); if (!isNaN(value)) { this.setData({ newThreshold: value }); } }, // 提交更新阈值(优化版) updateThreshold() { if (this.data.newThreshold === null || isNaN(this.data.newThreshold)) { wx.showToast({ title: '请输入有效数字', icon: 'error' }); return; } wx.showLoading({ title: '更新中...' }); wx.request({ url: 'https://soilgd.com:5000/update-threshold', method: 'POST', data: { threshold: this.data.newThreshold }, success: (res) => { if (res.statusCode === 200) { wx.showToast({ title: '更新成功' }); this.setData({ threshold: this.data.newThreshold }); } else { wx.showToast({ title: '更新失败', icon: 'error' }); } }, fail: (err) => { wx.showToast({ title: '网络错误', icon: 'error' }); }, complete: () => { wx.hideLoading(); } }); } });