简体   繁体   中英

calculator in express js, update answer in the same page

I build a simple express js calculator and I want the calculate to show the answer on the same page with the text boxes where I enter the numbers, now after I click calc I move to a blank page with the answer, instead I want a section under the calc button which show "Answer: XXX"

app.js

const  express= require("express");
const bodyParser=require("body-parser");
const app= express();
app.set('view engine', 'ejs');
app.use(bodyParser.urlencoded({extended:true}));
app.use(express.static("public"))

app.get("/",function(req,res){
    res.render('home');
});

app.get("/add",function(req,res){
    res.render('add');
});

app.post("/add",function(req,res){
    var num1=Number(req.body.n1);
    var num2=Number(req.body.n2);
    var result=num1+num2;
    res.send("Answer: "+result);
});

add.ejs

<!DOCTYPE html>
<html dir="rtl">
    <head>
        <title>calc add</title>
        <link rel="stylesheet" href="css/style.css" type="text/css">
    </head>
    <body>
        <form action="/add" method ="post">
            <input type="text" class="input" name="n1" placeholder="enter x1"><br>
            <br>
            <input type="text" class="input" name="n2" placeholder="enter x2"><br>
            <br>
            <button type="submit" class="submit" name="Submit">calc!</button>
        </form>
        <br>
        <a class="back" href="/">home</a>
    </body>
</html>

You can use fetch to make the POST request and get the answer.

<p id="result"></p>
<script>
document.querySelector('form').addEventListener('submit', function(e) {
    e.preventDefault();
    fetch(this.action, {method: this.method, body: new FormData(this)})
        .then(res => res.text()).then(ans => {
            document.getElementById("result").textContent = ans;
        });
});
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM