AcidNeutralizationModel.js 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120
  1. Page({
  2. data: {
  3. result: '', // 存储计算结果
  4. ph: '', // 土壤PH
  5. OM: '', // 有机质含量
  6. CL: '', // 土壤粘粒重量
  7. H: '', // 氢离子含量
  8. Al: '', // 铝离子含量
  9. showModal: false, // 控制弹窗显示与隐藏
  10. },
  11. // 更新输入数据
  12. onOMChange: function (e) {
  13. this.setData({
  14. OM: e.detail.value,
  15. });
  16. },
  17. onCLChange: function (e) {
  18. this.setData({
  19. CL: e.detail.value,
  20. });
  21. },
  22. onHChange: function (e) {
  23. this.setData({
  24. H: e.detail.value,
  25. });
  26. },
  27. onAlChange: function (e) {
  28. this.setData({
  29. Al: e.detail.value,
  30. });
  31. },
  32. onPhChange: function (e) {
  33. this.setData({
  34. ph: e.detail.value,
  35. });
  36. },
  37. // 页面加载时处理传递过来的数据(仅初始化,不提示错误)
  38. onLoad: function (options) {
  39. const encodedResult = options.result || ''; // 如果没有结果传递,设置为空字符串
  40. if (encodedResult) {
  41. try {
  42. // 解码URL编码的字符串
  43. const decodedResult = decodeURIComponent(encodedResult);
  44. console.log('解码后的数据:', decodedResult);
  45. // 将解码后的字符串解析为JSON对象
  46. const resultArray = JSON.parse(decodedResult);
  47. // 检查数组是否有效并显示第一个结果
  48. if (Array.isArray(resultArray) && resultArray.length > 0) {
  49. this.setData({
  50. result: resultArray[0].toString(), // 显示第一个结果
  51. });
  52. }
  53. } catch (error) {
  54. console.error('解析结果失败:', error);
  55. }
  56. }
  57. },
  58. // 点击按钮后进行计算并提示结果
  59. calculate: function () {
  60. console.log('开始计算...');
  61. const data = {
  62. model_name: 'rf_model_1214_1008',
  63. parameters: {
  64. pH: this.data.ph,
  65. OM: this.data.OM,
  66. CL: this.data.CL,
  67. H: this.data.H,
  68. Al: this.data.Al,
  69. },
  70. };
  71. wx.request({
  72. url: 'http://localhost:5000/predict',
  73. method: 'POST',
  74. data: JSON.stringify(data),
  75. header: {
  76. 'content-type': 'application/json',
  77. },
  78. success: (res) => {
  79. console.log('预测结果:', res.data.predictions);
  80. // 更新计算结果
  81. if (Array.isArray(res.data.predictions) && res.data.predictions.length > 0) {
  82. this.setData({
  83. result: res.data.predictions[0].toString(),
  84. showModal: true, // 显示弹窗
  85. });
  86. wx.showToast({
  87. title: '计算完成!结果已更新',
  88. icon: 'success',
  89. });
  90. } else {
  91. wx.showToast({
  92. title: '服务器返回数据格式有误',
  93. icon: 'none',
  94. });
  95. }
  96. },
  97. fail: (error) => {
  98. console.error('请求失败:', error);
  99. wx.showToast({
  100. title: '计算失败,请重试',
  101. icon: 'none',
  102. });
  103. },
  104. });
  105. },
  106. // 关闭弹窗
  107. closeModal: function () {
  108. this.setData({
  109. showModal: false, // 隐藏弹窗
  110. });
  111. },
  112. });