简体   繁体   中英

Displaying from Nodejs ExpressJS route to EJS view

I render the calc.ejs from calc.js router like this:

// calc.js router
router.get('/calc', function(req, res, next) {
  res.render('calc', {page:'Calculator', menuId:'Calculator', result: ''});
});

My calc.ejs is:

// calc.ejs view
<form action="/user/calc" method="post">
    <input type="number" name="num1"/><br/>
    <input type="number" name="num2"/>

    <input type="submit" value="Submit"/>

</form>   

<% if( result ){ %>
    <p> Display result here!!! :  < %= result %> </p>
  <% } else{ %>  
    <h1>No Result</h1>
 <% } %>

And I have my calc.js controller which takes two numbers, calculates and returns them as json, but I want to display the result in the paragraph element in calc.ejs

// calc.js controller
exports.calc = (req, res, next) => {
    let rezz = Number(req.body.num1) + Number(req.body.num2)   

    res.status(200).json({
      result: rezz
    });
 }

I get this json:

{"result":46} 

My question is why the result doesn't display in <p> element but comes as json, and how to display it there..

Thanks in advance !

In ejs:

< %= result %>  // this is wrong
<%= result %>   // this is right

In your controller, you can direct render your view and it should be:

exports.calc = (req, res, next) => {
    let rezz = Number(req.body.num1) + Number(req.body.num2) 
    res.render('calc',{
        page:'Calculator', 
        menuId:'Calculator',
        result: rezz
    });
 }

you can again render view in calc function

exports.calc = (req, res, next) => {
    let rezz = Number(req.body.num1) + Number(req.body.num2)   
     return res.render('calc', {page:'Calculator', menuId:'Calculator', result: rezz });
 }

if you want to use json then you have to call ajax function on form submit and send request and display returned response in view

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