我正在嘗試使用 express.js 創建一個計算器應用程式,以獲取對 html 檔案的請求和一個接受用戶輸入并以答案回應的發布請求。但是,我想在沒有頁面重定向的情況下在 html 容器中顯示我的答案。有沒有辦法用香草 javascript 來實作這一點?
索引.html
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="stylesheet" href="styles.css" />
<link rel="shortcut icon" href="#" />
<title>Calculator</title>
</head>
<body>
<h1>Calculator App</h1>
<form action="/" method="post" class="ajax">
<label for="userInput">Enter Equation</label>
<input type="text" id="equation" name="equation" />
<button type="submit" id="btn_submit">Calculate</button>
</form>
<div class="container"></div>
</body>
</html>
應用程式.js
const express = require('express');
const app = express();
port = 3000;
app.use(express.urlencoded({ extended : false }));
app.use(express.static('public'));
app.get('/', (req, res) => {
res.sendFile(__dirname public);
});
app.post('/', (req, res) => {
let equation = req.body.equation;
console.log(equation);
let result = eval(equation);
res.status(200).send('Result is ' result);
});
app.listen(port, ()=> {
console.log('Hosted on port: ' port);
});
CalculatorApp 評估運算式
uj5u.com熱心網友回復:
您將需要撰寫前端 JavaScript 代碼來發出 ajax 請求,而不是讓表單操作提交請求。JavaScript 將接收回應并可以更新 HTML 上的值。
app.post('/', (req, res) => {
let equation = req.body.equation;
console.log(equation);
let result = eval(equation);
res.status(200).json({ value: `Result is ${result}` });
});
<script>
document.querySelector('form').addEventListener('submit',submitEquation);
function submitEquation(event){
event.preventDefault();
const input = document.querySelector('#equation');
const equation = input.value;
const clearInput = true;
if(clearInput){
input.textContent = '';
}
fetch(window.location.origin, {
method: 'post',
body: JSON.stringify({ equation })
})
.then(response => response.json())
.then(json => {
document.querySelector('.container').textContent = json.value;
})
}
</script>
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/489766.html
標籤:javascript html 节点.js 表示
