123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120 |
- Page({
- data: {
- result: '', // 存储计算结果
- ph: '', // 土壤PH
- OM: '', // 有机质含量
- CL: '', // 土壤粘粒重量
- H: '', // 氢离子含量
- Al: '', // 铝离子含量
- showModal: false, // 控制弹窗显示与隐藏
- },
- // 更新输入数据
- onOMChange: function (e) {
- this.setData({
- OM: e.detail.value,
- });
- },
- onCLChange: function (e) {
- this.setData({
- CL: e.detail.value,
- });
- },
- onHChange: function (e) {
- this.setData({
- H: e.detail.value,
- });
- },
- onAlChange: function (e) {
- this.setData({
- Al: e.detail.value,
- });
- },
- onPhChange: function (e) {
- this.setData({
- ph: e.detail.value,
- });
- },
- // 页面加载时处理传递过来的数据(仅初始化,不提示错误)
- onLoad: function (options) {
- const encodedResult = options.result || ''; // 如果没有结果传递,设置为空字符串
- if (encodedResult) {
- try {
- // 解码URL编码的字符串
- const decodedResult = decodeURIComponent(encodedResult);
- console.log('解码后的数据:', decodedResult);
- // 将解码后的字符串解析为JSON对象
- const resultArray = JSON.parse(decodedResult);
- // 检查数组是否有效并显示第一个结果
- if (Array.isArray(resultArray) && resultArray.length > 0) {
- this.setData({
- result: resultArray[0].toString(), // 显示第一个结果
- });
- }
- } catch (error) {
- console.error('解析结果失败:', error);
- }
- }
- },
- // 点击按钮后进行计算并提示结果
- calculate: function () {
- console.log('开始计算...');
- const data = {
- model_name: 'rf_model_1214_1008',
- parameters: {
- pH: this.data.ph,
- OM: this.data.OM,
- CL: this.data.CL,
- H: this.data.H,
- Al: this.data.Al,
- },
- };
- wx.request({
- url: 'http://localhost:5000/predict',
- method: 'POST',
- data: JSON.stringify(data),
- header: {
- 'content-type': 'application/json',
- },
- success: (res) => {
- console.log('预测结果:', res.data.predictions);
- // 更新计算结果
- if (Array.isArray(res.data.predictions) && res.data.predictions.length > 0) {
- this.setData({
- result: res.data.predictions[0].toString(),
- showModal: true, // 显示弹窗
- });
- wx.showToast({
- title: '计算完成!结果已更新',
- icon: 'success',
- });
- } else {
- wx.showToast({
- title: '服务器返回数据格式有误',
- icon: 'none',
- });
- }
- },
- fail: (error) => {
- console.error('请求失败:', error);
- wx.showToast({
- title: '计算失败,请重试',
- icon: 'none',
- });
- },
- });
- },
- // 关闭弹窗
- closeModal: function () {
- this.setData({
- showModal: false, // 隐藏弹窗
- });
- },
- });
|