Course for This Assignment | https://bbs.csdn.net/forums/ssynkqtd-04 |
Assignment Requirements | https://bbs.csdn.net/topics/617378696 |
Objectives of This Assignment | Learn the development of front and back end and perfect the function of the first calculator. |
Student ID | 832101201_王心怡_21124477 |
Github links about the front-end | |
Github links about the back-end |
目录
III.Design and implementation process
v.Back-end background knowledge
I.Introduction
In this blog post, I will introduce the upgraded front end separation calculator. Its basic functions include addition, subtraction, multiplication, division and remainder, and its extended functions include radical sign, trigonometric function, logarithm, scientific notation, bracket calculation, reciprocal and power operation. The front end uses HTML+JS+CSS, and the back end uses MySQL and node.js.
II.PSP table
**Personal Software Process Stages** | Estimated Time(minutes) | Actual Time(minutes) |
Planning | ||
• Estimate | 60 | 45 |
Development | ||
• Analysis | 25 | 30 |
• Design Spec | 8 | 8 |
• Design Review | 5 | 8 |
• Coding Standard | 30 | 40 |
• Design | 15 | 20 |
• Coding | 250 | 350 |
• Code Review | 60 | 30 |
• Test | 25 | 30 |
Reporting | ||
• Test Repor | 65 | 60 |
• Size Measurement | 10 | 10 |
• Postmortem & Process Improvement Plan | 40 | 60 |
**Sum** | 593 | 691 |
III.Design and implementation process
i. Interface design
Based on the previous interface design, I added a new CSS style that uses the :hover pseudo-class selector to define the style of the button over the mouse. button:hover means to select the style of all buttons when hovering, turning brown when hovering over a number button and pink when hovering over other buttons. The background-color property sets the button's background color to blue. Use the button element with the "class" attribute to "digit" to set it separately so that the background color of the number button is orange and the rest of the keys are white.
//Mouse hover: When you press the button,
the position of the mouse will change to a different color
button {
padding: 5px;
background-color: #ffffff;
border: none;
cursor: pointer;
}
button:hover {
background-color: #ff00956c;
color: #ffffff;
}
button.digit {
background-color: #ff7b1d;
color: #ffffff;
}
button.digit:hover {
background-color: #c9500a;
}
//Part of the button code display:
<button onclick="appendChar('*')">*</button>
<button onclick="appendChar('1')" class="digit">1</button>
<button onclick="appendChar('2')" class="digit">2</button>
<button onclick="appendChar('3')" class="digit">3</button>
<button onclick="appendChar('-')">-</button>
<button onclick="appendChar('.')">.</button>
ii.Calculation logic
The following is JavaScript code, most of which comes with its own functions:
1. The 'calculateTan()', 'calculateLog10()', 'calculateLn()' functions are all function values that compute input values and display the result in a text box named 'result'. It evaluates the input value using the Math.() function and assigns the result to result.value.
2. ` calculateScientificNotation ()' function is used for converting the input value science and counting method, and the results show that in a ` result ` text box. It computes the input value into a number using the 'eval()' function, then converts the result into scientific notation using the 'toExponential()' method, and assigns the result to 'result.value'.
3. The 'calculatePower()' function is used to calculate the exponential power of the input value and displays the result in a text box named 'result'. It first splits the input value according to the "^" symbol to get the base and exponent, then uses the 'Math.pow()' function to compute the exponential power of the base, and assigns the result to 'result.value'.
4. The 'calculateInverse()' function is used to calculate the inverse of the input value and displays the result in a text box named 'result'. It uses the 'eval()' function to evaluate the input value as a number, then calculates its reciprocal, and assigns the result to result.value.
5.'appendChar()' The function accepts an argument called "char" to indicate the character to append. It adds the character directly to a string variable named "expression". Parentheses and other simple operations are implemented through it.
function appendChar(char) {
let result = document.getElementById("result").value;
document.getElementById("result").value = result + char;
}
function calculateTan() {
try {
result.value = Math.tan(eval(result.value));
} catch (error) {
result.value = 'ERROR';
}
}
function calculateLog10() {
let result = document.getElementById("result").value;
let calculatedResult = Math.log10(eval(result));
document.getElementById("result").value = calculatedResult;
}
function calculateLn() {
let result = document.getElementById("result").value;
let calculatedResult = Math.log(eval(result));
document.getElementById("result").value = calculatedResult;
}
function calculateScientificNotation() {
try {
result.value = eval(result.value).toExponential();
} catch (error) {
result.value = 'ERROR';
}
}
function calculatePower() {
let result = document.getElementById("result").value;
let parts = result.split('^');
if (parts.length === 2) {
let base = parseFloat(parts[0]);
let exponent = parseFloat(parts[1]);
let calculatedResult = Math.pow(base, exponent);
document.getElementById("result").value = calculatedResult;
}
}
function calculateInverse() {
let result = document.getElementById("result").value;
let calculatedResult = 1 / eval(result);
document.getElementById("result").value = calculatedResult;
}
Computing function display:
计算器功能升级
iii.Local storage
If we're not thinking about using the back end, here's how local caching works:
1. Features: Data is stored in the browser and will not be lost with page refresh. Large amounts of data can be stored without taking up browser memory. Stored data can be persisted across sessions, even if the user closes the browser and opens it again. Data is stored in the form of key-value pairs, and only string type data can be stored, if you need to store other types of data, you need to serialize and deserialize operations.
2. Code idea: First, it retrieves the previously saved history from localStorage, parses it into an array if it exists, and creates an empty array if it does not exist.
Next, it assembles the current result of the evaluation and the expression into a string and adds it to the history array. It then saves the updated history array to localStorage again.
The function displayHistory() is used to display the history list. It first calls the getPreviousResults() function to asynchronously fetch the history array and then empties the contents of the history list. Next, it traverses the history array, creating a <li> element for each history, and adding the expression and result to that element.
Finally, it adds the element to the history list.
The clearHistory() function is used to clear the history. It calls the removeHistory() function to asynchronously delete the history, and then calls the displayHistory() function to redisplay the updated history list.
/ 将历史记录保存到localStorage中
let history = localStorage.getItem("history");
if (history) {
history = JSON.parse(history);
} else {
history = [];
}
history.push(result + " = " + calculatedResult);
localStorage.setItem("history", JSON.stringify(history));
}
async function displayHistory() {
let history = await getPreviousResults()
console.log(history, 'history');
let historyList = document.getElementById("history-list");
historyList.innerHTML = "";
for (let i = 0; i < history.length; i++) {
let item = document.createElement("li");
item.textContent = `${history[i].expression}=${history[i].result}`;
historyList.appendChild(item);
}
}
function clearHistory() {
// localStorage.removeItem("history");
removeHistory().then(res => {
displayHistory();
})
}
本地储存历史记录
iv.Back-end implementation
There is a lot of code, you can click "ass2history" in github above to see.
1.Connection
Communicate with the server and process the saving and obtaining of the results, using jQuery's '$.ajax()' method to make HTTP requests and process responses. The url attribute specifies the URL of the server, the type attribute specifies the type of request (POST or GET), and the data attribute specifies the data to be sent. The successful callback function is defined with the 'success' attribute, and the wrong callback function is defined with the 'error' attribute. The XMLHttpRequest object is used to send the HTTP request and process the response, and the result of the asynchronous request is processed through an event listener.
(1) 'saveResult(expression, result)' : This function uses the '$.ajax()' method to send a POST request to the server, sending the expression and the result as data. After the result is saved successfully, the 'displayHistory()' function is called to display the history.
(2) 'getPreviousResults()' : This function returns a Promise object and sends a GET request to the server using the '$.ajax()' method to retrieve the previously saved result. When the result is successfully obtained, it is passed as an argument to the Promise object's 'resolve()' method.
(3) 'removeHistory()' : This function returns a Promise object and uses the '$.ajax()' method to send a POST request to the server to delete the previously saved result. When the result is successfully deleted, it is passed as an argument to the Promise object's 'resolve()' method.
(4) The calculate() function is used to send the expression entered by the user to the back end for calculation and display the calculation result on the page. The code takes the value of the input box, then creates an XMLHttpRequest object and sends the input string to the '/calculate' path on the back end using a POST request. Set the Content-Type of the request header to application/json. The onreadystatechange event listener is then used to listen for the status change of the request, and when the status of the request is 4 (completed) and the status code is 200 (successful), the result in the response is parsed and the result is displayed on the page.
(5) The'retrieveHistory()' function is used to retrieve the history from the back end and display the history on the page. The code also creates an XMLHttpRequest object that uses a GET request to retrieve the history from the '/history' path on the back end. Again, the onreadystatechange event listener listens for state changes in the request, and when the request status is 4 (completed) and the status code is 200 (successful), the history in the response is parsed, and each history is created as a div element, which is then added to the page.
2.Archive
The mysql module is used to connect to and manipulate the MySQL database, and the express module is used to create and run the server. The express.json() and express.urlencoded() middleware are used to parse the requested JSON and URL-encoded data.
(1) 'saveResult' : This endpoint is used to receive the user's expression, evaluate the result, and save the expression and result to the database. It defines a POST request handler using the app.post() method. Inside the handler, it takes the expression from the body of the request, evaluates the result using JavaScript's 'eval()' method, and inserts the expression and result into a database table called 'history'.
(2) 'getPreviousResults' : This endpoint is used to get the previously saved history. It defines a GET request handler using the app.get() method. Inside the handler, it queries the last 10 records from the 'history' table and sends the results to the client.
(3) 'removePreviousResults' : This endpoint is used to delete previously saved history. It defines a POST request handler using the app.post() method. Inside the handler, it executes a 'TRUNCATE TABLE' SQL statement to delete all records in the 'history' table.
3. Back-end function display
储存历史记录
v.Back-end background knowledge
1. Software introduction
Node.js is a JavaScript runtime environment based on the Chrome V8 engine that can be used to build high-performance web applications. Node.js processes requests in an event-driven and non-blocking I/O manner, making it ideal for handling highly concurrent network applications. MySQL is a popular open source relational database management system that is widely used to store and manage data. MySQL, as a relational database, can store and manage a large amount of data, and provides powerful query and transaction processing functions.
2. Combine the two
It's easy to build projects using Node.js and MySQL. We can use Node.js' module manager and package manager to handle dependencies and easily connect to MySQL database using MySQL module. Handle HTTP requests and responses by using the Express framework and writing a route. By combining these technologies, we can quickly build a complete project.
3. Flow chart
IV. Summary
In this assignment, I learned how front end and back end combine. In order to make the interface of the calculator more beautiful, I set the mouse hover function. I learned other functions in order to implement other additional computing functions. Before starting the database setup process, you need to ensure that Node.js and MySQL are properly installed and configured. This includes installing the relevant software packages, setting up environment variables, and ensuring that they work properly. I spent a lot of time installing it, and it was a long and lonely process, solving bug after bug, exercising my patience and carefulness.