【问题标题】:Taking input from form, retrieving data from database and showing output从表单中获取输入,从数据库中检索数据并显示输出
【发布时间】:2017-09-16 00:19:10
【问题描述】:

我正在使用 nodejs、express 和 mongodb。我正在使用 cloud9 IDE

我想创建一个带有表单的页面,该表单接受用户的输入,从数据库中搜索相应的数据并在同一页面上显示该数据(重新加载后),如果数据不存在则显示特定的响应。

这就是我所做的-

路线-

app.get("/",function(req,res){
var asked = req.query.asked;
  Name.findOne({name:asked},function(err,foundAsked){
      if(err){console.log("ERROR!!!");}
      else{res.render("Landing.ejs",{foundAsked:foundAsked}); }
  });
 }); 

EJS 文件-

//Form takes name as input from the user

<form >
    <input type="text" name="asked" action="/" method="GET">
    <button class="button">Submit</button>
</form>



//If data is found last name is returned
<% if(foundAsked){ %>
    <h2 >  <%= foundAsked.Lastname %> </h2>
<% } %>


 //blank space stays there which is replaced by a response,if after 
   //submission nothing is found
<% if(!foundAsked){ %>
    <h5></h5> 
<% } %>

JS-

 $(".button").click(function(){

          $("h5").text("No data present");
 });

但问题是,如果没有找到数据,则显示响应,但它只停留在页面重新加载之前的时间。 我试图寻找答案,但我没有找到任何答案。请帮助

【问题讨论】:

  • 完整的 URL(包括参数)是什么样子的?
  • 当您执行console.log(foundAsked) 时,您会在控制台中得到什么?
  • 它是我的主页,所以 URL 只是“/”,我也在问题中编辑了它。@ShimonBrandsdorfer
  • url 是否会因重新加载而改变?
  • 我得到- { _id:某事,名称:'abc',姓氏:'xyz'} @ShimonBrandsdorfer

标签: javascript html css node.js express


【解决方案1】:

你想显示的文字,只有在点击button后才会出现,一旦重新加载,你必须再次点击(点击会显示文字,并触发重新加载,所以文字会再次消失)。

您需要有另一个按钮(不会提交)来触发此消息。或者更确切地说,为什么不最初显示(将此内联放在&lt;h5&gt; 标签内)?

您需要区分“无数据”或“无查询”。 您可以在后端执行此操作,类似于以下内容:

app.get("/",function(req,res){
var asked = req.query.asked;
  Name.findOne({name:asked},function(err,foundAsked){
      if(err){console.log("ERROR!!!");}
      else{res.render("Landing.ejs",{foundAsked:foundAsked, asked: asked}); }
  });
 }); 

然后在Landing.ejs:

<% if(!foundAsked && asked){ %>
        <h5>No data present</h5> 
  <% } %>

【讨论】:

  • 但是,由于 foundAsked 最初是未定义的(在提交表单之前),它会显示响应而不需要输入本身。我想显示它,如果 foundAsked 未定义,即使在表单之后提交。
  • 非常感谢,工作非常顺利。再次感谢 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-08-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多