thres.js 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. // pages/threshold/threshold.js
  2. Page({
  3. data: {
  4. threshold: null, // 初始化为null
  5. newThreshold: null,
  6. loading: true // 添加加载状态
  7. },
  8. onLoad() {
  9. this.getThreshold();
  10. },
  11. // 获取当前阈值(优化版)
  12. getThreshold() {
  13. this.setData({ loading: true });
  14. wx.request({
  15. url: 'https://soilgd.com:5000/get-threshold',
  16. success: (res) => {
  17. if (res.statusCode === 200 && res.data && typeof res.data.current_threshold === 'number') {
  18. this.setData({
  19. threshold: res.data.current_threshold,
  20. });
  21. } else {
  22. wx.showToast({ title: '数据格式错误', icon: 'error' });
  23. console.error('Invalid response:', res);
  24. }
  25. },
  26. fail: (err) => {
  27. wx.showToast({ title: '请求失败', icon: 'error' });
  28. console.error('API Error:', err);
  29. },
  30. complete: () => {
  31. this.setData({ loading: false });
  32. }
  33. });
  34. },
  35. // 输入框改变事件(添加校验)
  36. onInput(e) {
  37. const value = Number(e.detail.value);
  38. if (!isNaN(value)) {
  39. this.setData({
  40. newThreshold: value
  41. });
  42. }
  43. },
  44. // 提交更新阈值(优化版)
  45. updateThreshold() {
  46. if (this.data.newThreshold === null || isNaN(this.data.newThreshold)) {
  47. wx.showToast({ title: '请输入有效数字', icon: 'error' });
  48. return;
  49. }
  50. wx.showLoading({ title: '更新中...' });
  51. wx.request({
  52. url: 'https://soilgd.com:5000/update-threshold',
  53. method: 'POST',
  54. data: { threshold: this.data.newThreshold },
  55. success: (res) => {
  56. if (res.statusCode === 200) {
  57. wx.showToast({ title: '更新成功' });
  58. this.setData({ threshold: this.data.newThreshold });
  59. } else {
  60. wx.showToast({ title: '更新失败', icon: 'error' });
  61. }
  62. },
  63. fail: (err) => {
  64. wx.showToast({ title: '网络错误', icon: 'error' });
  65. },
  66. complete: () => {
  67. wx.hideLoading();
  68. }
  69. });
  70. }
  71. });