[作业2] Javascript Caculator

832101129傅安 2023-10-22 16:45:32

 一、Introduction

  • Implement a simple calculator with javascript

 

二、Personal Information

Github:GitHub - 1ro1/caculator

The Aim of This A web Calculator
     MU STU ID and FZU STU ID21144249_832101129

三、Time Table

Personal Software Process Stages

Estimated Time(minutes)Actual Time(minutes
Planning2530
Estimate2530
Development2530
Analysis2530
Design Spec2530
Design Review 2530
Coding Standard 2530
Design2530
Coding2530
 Code Review2530
Test2530
Reporting2530
Test Repor 2530
Size Measurement2530
Postmortem & Process Improvement Plan2530
Sum400480

四、code

Main process

back-end:  creating a host using Flask

front-end:  send message to host

sql:  get message from host when host get message

 

 

 

front-end

 

1.send message

function calculate() {
    try {
        let expression = display.value;
        display.value = format(eval(display.value.replace(/lg/g, 'Math.log10').replace(/ln/g, 'Math.log').replace(/sqrt/g, 'Math.sqrt').replace(/sin/g, 'Math.sin').replace(/\^/g, '**').replace(/cos/g, 'Math.cos').replace(/tan/g, 'Math.tan').replace(/e/g, 'Math.E').replace(/pi/g, 'Math.PI').replace(/abs/g, 'Math.abs')));
        let result = display.value;

        const xhr = new XMLHttpRequest();
        xhr.open('POST', 'http://localhost:5000/post', true);
        xhr.setRequestHeader('Content-type', 'application/json');
        xhr.onreadystatechange = function() {
            if (xhr.readyState === 4) {
              if (xhr.status === 200) {
                const response = xhr.responseText;
                console.log(response);
              } else {
                console.error('请求失败,状态码:' + xhr.status);
              }
            }
          };

        const data = {
            expression: expression,
            result: result
        };
        xhr.send(JSON.stringify(data));
    } catch (error) {
        display.value = 'Error';
    }
}

2.get message

function getHistory() {
    const xhr = new XMLHttpRequest();
    xhr.open('GET', 'http://localhost:5000/get', true);
    xhr.onreadystatechange = function () {
      if (xhr.readyState === 4) {
        if (xhr.status === 200) {
            Data = JSON.parse(xhr.responseText);
            array = Data["data"];
            console.log(array)
            let string = "";
            for(let i = 0; i < array.length; i++) {
                string += array[i][0] + " = " + array[i][1] + "\n"
            }
            history.value = string;
        } else {
            console.error('获取数据出错: ' + xhr.status);
        }
      }
    };
    xhr.send();
}

3.clear history

function clearHistory() {
    const xhr = new XMLHttpRequest();
    xhr.open('POST', 'http://localhost:5000/send_clear', true);
    xhr.onreadystatechange = function () {
        if (xhr.readyState === 4 && xhr.status === 200) {
            console.log(xhr.responseText);
        }
    };
    xhr.send();

    history.value = "";
}

 

back-end

 

1.get message and send to mysql

@app.route('/post', methods=['POST'])
def post_history(): #存储运算表达式和值
    try:
        data = request.get_json()  # 获取POST请求的JSON数据
        expression = data.get('expression')
        result = data.get('result')

        time = datetime.datetime.now()

        data = (time, expression, result)
        insert = "INSERT INTO equation VALUES (%s, %s, %s)" #sql插入语句
        cursor.execute(insert, data)
        conn.commit()

        response_message = "ok"
        return jsonify({"message": response_message})

    except Exception as e:
        error_message = str(e)
        return jsonify({"error": error_message}), 500

2.get message from mysql and send to front-end

@app.route('/get', methods=['GET'])
def get_calculation_data():#得到历史值
    try:
        cursor.execute("SELECT expression, result FROM equation ORDER BY time DESC LIMIT 10")
        data = cursor.fetchall()
        return jsonify({"data": data})

    except Exception as e:
        error_message = str(e)
        return jsonify({"error": error_message}), 500

3.clear data in mysql

@app.route('/send_clear', methods=['POST'])
def send_clear():#清除数据库
    try:
        insert = "DELETE FROM equation"
        cursor.execute(insert)
        conn.commit()

        response_message = "ok"
        return jsonify({"message": response_message})

    except Exception as e:
        error_message = str(e)
        return jsonify({"error": error_message}), 500

 

五、Summary

      In this assignment, I learned some sql and back-end knowledge.

...全文
44 回复 打赏 收藏 转发到动态 举报
写回复
用AI写文章
回复
切换为时间正序
请发表友善的回复…
发表回复

176

社区成员

发帖
与我相关
我的任务
社区描述
梅努斯软件工程
软件工程 高校 福建省·福州市
社区管理员
  • LinQF39
  • Jcandc
  • chjinhuu
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧