Assignment2: A calculator that implements front - and back-end interaction


Introduction

  In this blog post, I will detail the implementation process of the front-end and back-end interactive WeChat applet calculator and show the final product.

  This calculator I created can implement addition, subtraction, multiplication, division, backspace and ans operations (get history). Before implementing the back-end database, I found a problem with my calculator, that is, I didn’t take into account the special case of 0, which can’t divide by 0 and balance to 0. I fixed this problem with this update.


The Link of Classhttps://bbs.csdn.net/forums/ssynkqtd-04
The Link of Requirement of This AssignmentSecond assignment-- Back-end separation calculator programming-CSDN社区
The Aim of This AssignmentImprove the function of calculator and realize front-end interaction
MU STU ID and FZU STU ID21124841_832101219

Link here to the project code:https://github.com/cxlyk/Bruce.git

I.PSP Table

Personal Software Process StagesEstimated Time(minutes)Actual Time(minutes)
Planning4050
• Estimate4050
Development365500
• Analysis2530
• Design Spec2040
• Design Review1020
• Coding Standard1010
• Design6080
• Coding140140
• Code Review6075
• Test4050
Reporting120150
• Test Repor6080
• Size Measurement1010
• Postmortem & Process Improvement Plan3060
Sum525700

II.Problem-solving ideas

Front-end design concepts: along the lines of WeChat applets:

  1. wxml structure: Create a wxml file to define the applet page. Add input boxes, buttons and other elements to allow users to enter mathematical expressions and perform calculations.

  2. wxss Styles: Use wxss to beautify the page and make it look more beautiful and easy to use. You can add styles like background, font, colour and layout. I used gradient colour to make the background look better.

  3. Js Interaction: Use the .js file of WeChat app to write the front-end logic and implement the function:

  • Listen to button click events to capture user input.
  • Handle expression evaluation when user clicks on the equal sign
    button.
  • Display the result of the calculation on the web page.

4.User Experience: Ensure the interface is user friendly and easy to use. Add error handling features, (which was not available last time) such as divide by zero and remainder to zero errors to enhance logic and improve user experience.

Backend Design Ideas:
I wasted a lot of time before finding the right approach. My first thought was to rent a server piggybacking on the database for connectivity, and then I found out that Huawei Cloud has a free cloud database rental (one month). After applying for it, I realised that I knew nothing about the database and API content, and had no idea where to start. Then I found out that there are private databases that I can rent, which are much easier to use compared to Huawei Cloud, and although the memory is small, it’s perfectly adequate.

1.Backend: Use WeChat apps to write the backend code, using post to ensure data security, so as to interact with the database and feed back to the front-end later.

2.API design: design two apis, respectively for storage and reading.

3.Database Connection: Use MySQL to connect to the database and perform the necessary database operations to store the calculation history.

4.Results Return: Send the stored expressions and their corresponding computations back to the front-end, usually in JSON format. Make sure to handle any potential errors or exceptions and provide friendly error messages.

III.Design and Implementation process

    After a week of studying and looking up information, I found a relatively workable way to combine a WeChat applet with a backend database. However, since I had studied microcontrollers before and had not been exposed to front-end and back-end stuff, I was a bit overwhelmed by using it. But fortunately, with my efforts, I was able to achieve the function of storing and reading calculator data.

    Firstly I found a website developed by an individual that offers a rental service for MySql databases and corresponding APIs. By using their database, I don’t need to build my own database on a server, which is the best way I could find.
Links to the sites I use:https://zbmysql.huaxio.cn/index.php

    Then there is the design of the WeChat applet part, for the new update of the division by 0 and the remainder of 0 part will be shown in the code section.
    I used tabbar operation to divide the applet page into two parts. On the left is the calculator page, switch to the right is the history query. This is the overall design. Regarding the data storage and reading part, I use the wx:require method, and use the post method to input the password of the database to ensure the security of data transmission. The specific code and explanation will be put in the code section.Flowchart of front - and back-end interactions

IV. Code Description

Here is the code that completes the functionality, regarding the division by 0 and remainder by 0 operations:

  case '÷':
        if (right == 0) { //如果数字不合规-除以0
        wx.showToast({
        title: "Can't divided by 0 !",
        icon: 'none'
        })
        ans = left
         } else {
          let _ans = acc.div(left, right)
          let x = String(_ans).indexOf('.') + 1;
          let y = String(_ans).length - x;
          if (y > 10) {
            ans = _ans.toFixed(10);
          } else {
            ans = _ans
          }
        }
        break;
      case '%':
         if (right == 0) { //如果数字不合规-余0
        wx.showToast({
        title: "Can't take a remainder of 0 !",
        icon: 'none'
       })
      ans = left
       } else {
       ans = left % right
       }
        break;
      default:
        ans = left
        break;

Here is the code to redesign the WeChat applet interface(Write it in a global json file):

"tabBar": {
    "list": [{
      "pagePath": "pages/index/index",
      "text": "calculator",
      "iconPath": "/pages/history/images/图标.jpg",
      "selectedIconPath": "/pages/history/images/图标.jpg"
    },{
      "pagePath":  "pages/history/history",
      "text": "ans_history",
      "iconPath": "/pages/history/images/3_static.png",
      "selectedIconPath": "/pages/history/images/3_active.png"
    }
  ]
  },

Here is the code for the data storage section(The history and result arrays are used to store the history and results of calculations.):

 numBtn(e) { 
// other logic
	if (!isNaN(num) || num === '.') { //.
        this.addToHistory(expression.join(' '));
      }
addToHistory(expression) {
  let historyItem = {
    expression: expression,
  };
  this.data.history.push(historyItem);
  this.setData({
    history: this.data.history
  });
}

history arrays:
    The history array is used to store the history of the user’s calculations. Each time the user completes a calculation, the addToHistory function is called to add the current expression to the history array.
    The addToHistory function takes an expression argument, wraps it into an object, and adds the object to the history array.
    this.data.history.push(historyItem) adds the new calculated history item to the history array.
    this.setData({ history: this.data.history }) Updates the applet’s data, ensuring that the calculation history on the page is updated.

finish(e) {
  // ...(计算逻辑)

  // 将计算结果加入 result 数组
  this.data.result.push(expression[0]);

  // 更新数据
  this.setData({
    'counter.expression': expression,
    'counter.ansType': ansType,
    equalButtonCount: this.data.equalButtonCount + 1,
    result: this.data.result
  });

  // 发送请求将历史记录存入数据库(在这之前确保 this.data.history 和 this.data.result 已经准备好了)
  wx.request({
    url: "https://zbmysql.huaxio.cn/api/15260107375uMTIC.php?",
    data: {
      sql: 'INSERT INTO new_calcultor VALUES( null, "' + this.data.history[this.data.equalButtonCount].expression + '","=","' + this.data.result[this.data.equalButtonCount] + '");',
      api_pawsord: "wdmpOtiaZhFkKv6"
    },
    method: 'post',
    header: {
      "Content-Type": "application/x-www-form-urlencoded"
    },
    dataType: 'json',
    responseType: 'text',
    success: (res) => {
      console.log(res.data);
      if (res.data.affected = 1) {
        console.log('操作成功!');
      }
    },
    fail: () => {},
    complete: () => {},
  });
}

The result array:
    The result array is used to store the results of each calculation. In the finish function, when you finish a calculation, you add the result to the result array and save it in setData.
    In the finish function, when the calculation is complete, the current result of the calculation, expression[0], is added to the result array.
The result array is updated in setData.
    When the request is sent, get the current number of button clicks from this.data.equalButtonCount, and get the corresponding expression and result from the history and result arrays.

Here is a demonstration of the operating system storing data:

storing data

The following code reads data from the database:

.wxml:
<button bindtap="sec_bt">Click for historical data</button>
<view class="view1">
<view>{{data1a}}</view> <!-- 用于显示从数据库获取的数据 -->
<view>{{data1b}}</view>
<view>{{data1c}}</view>
</view>

<view class="view1">
<view>{{data2a}}</view> 
<view>{{data2b}}</view>
<view>{{data2c}}</view>
</view>
.js:
sec_bt() {
    wx.request({
      url: "https://zbmysql.huaxio.cn/api/15260107375uMTIC.php?", // 请求的API地址
      data: {
        sql: 'select *  from new_calcultor where id="1";', // SQL语句
        api_pawsord: "wdmpOtiaZhFkKv6" // API密码
      },
      method: 'post',
      header: {
        "Content-Type": "application/x-www-form-urlencoded"
      },
      dataType: 'json',
      responseType: 'text',
      success: (res) => {
        console.log(res.data) // 得到返回的数据
        this.setData({
          data1a: res.data.result[0].expression,
          data1b: res.data.result[0].equal,
          data1c: res.data.result[0].result,
        });
      },
      fail: () => {},
      complete: () => {}
    });
       wx.request({
      url: "https://zbmysql.huaxio.cn/api/15260107375uMTIC.php?", // 请求的API地址
      data: {
        sql: 'select *  from new_calcultor where id="2";', // SQL语句
        api_pawsord: "wdmpOtiaZhFkKv6" // API密码
      },
      method: 'post',
      header: {
        "Content-Type": "application/x-www-form-urlencoded"
      },
      dataType: 'json',
      responseType: 'text',
      success: (res) => {
        console.log(res.data) // 得到返回的数据
        this.setData({
          data2a: res.data.result[0].expression,
          data2b: res.data.result[0].equal,
          data2c: res.data.result[0].result,
        });
      },
      fail: () => {},
      complete: () => {}
    });

This is only part of it, because to display ten entries, another eight requests are needed, and only the id and data binding parts need to be changed. The data in the database consists of three parts, the first is the expression, the second is the equals sign and the last is the result.
this.setData({
data1a: res.data.result[0].expression,
data1b: res.data.result[0].equal,
data1c: res.data.result[0].result,
});

V. Video Demonstration

This video is a demonstration of the prohibition of division by 0 and remainder 0:

new function

This video is calculate ten results, pressing is equivalent to automatically storing the data in the database (new_caculator):

Calculator Calculator


在这里插入图片描述
                    The database after calculation

This video is a demonstration of a history query:

history query

在这里插入图片描述
An online experiential version of the applet

VI.Summary and Reflection

    This assignment has given me a good understanding of how WeChat applets are connected to the back-end database. However, I personally feel that there must be a better way to be able to achieve the functionality, and there are still a lot of inadequacies in my project. I will need to continue to study it when I have time afterwards

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

832101219林泳坤

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值