2017-02-13 50 views
1

我有一个表单页面,在用户填写表单并点击提交按钮后,应该显示成功警报(Boostrap)。在Node中使用POST操作后在EJS中更改元素样式 - Express

<form class="well form-horizontal" action="/contact" method="post" id="contact_form"> 

... (input fields here) 

<div class="alert alert-success" role="alert" id="success_message"> Success 
    <i class="glyphicon glyphicon-thumbs-up" ></i> Thanks for contacting us, we will get back to you shortly. 
</div> 

<div class="form-group"> 
    <label class="col-md-3 control-label"></label> 
    <div class="col-md-6"> 
    <button type="submit" class="btn btn-warning" > Submit <span class="glyphicon glyphicon-send"></span></button> 
    </div> 
</div> 

默认情况下,在我的CSS:

#success_message { display: none; } 

如何更改显示属性不none(块,内联,内联块),以便出现成功警报消息,后Node-Express中的POST操作?

var router = express.Router(); 

router.post('/', function(req, res, next) { 

    const data = { 
     fname: req.body.name, 
     lname: req.body.lname, 
     ... 
     comment: req.body.comment 
    } 

    // insert data using SQL/MongoDB library 
    // refresh same page if success, the input elements cleared 
    // and show the success alert or fail alert div in rendered HTML 

     res.render('contact', { 
      fname :  '' 
      lname :  '' 
      ... 
      comment : '' 
     }); 

}); 

是否有可能没有jQuery做到这一点?我不喜欢使用jQuery。

回答

1

方法1:

首先在GET请求中添加success属性进行渲染。仅在验证

router.post('/', function(req, res, next) { 
    ... 
    ... 
     res.render('contact', { 
      fname: '',    
      ........ 
      success: true 
     }); 
    }); 

在你EJS后像

router.get('/', function(req, res, next) { 
... 
... 
    res.render('contact', { 
     fname: '',    
     ........ 
     success: false 
    }); 
}); 

,并在后期,文件,你可以这样做

<% if (success) { %> 
    <div class="alert alert-success" role="alert" id="success_message"> Success 
     <i class="glyphicon glyphicon-thumbs-up" ></i> Thanks for contacting us, we will get back to you shortly. 
    </div> 
<% } %> 

也可用于错误上述方法。

方法2:

更改CSS是有点太复杂了,你可以改变类或ID来代替。 (随时改变的类,而不是IDS)

#id1 { 
... 
} 

#id2 { 
... 
} 
<div class="alert alert-success" role="alert" id=<%= success ? "id1" : "id2" %>> Success 
    <i class="glyphicon glyphicon-thumbs-up" ></i> Thanks for contacting us, we will get back to you shortly. 
</div> 
相关问题