节点js如何将数据传递给静态html作为对Ajax调用的响应

。 首先,我是节点中的新手。 我已经阅读了几乎所有类似的post,但无法弄清楚我的情况最好。 我从一个静态html文件发送一个房间名称joinajax发布请求。 在服务器端,我search我的mongodb,如果有这个特定名称的房间。 如果没有,我想回到上一页发送一个消息,如“没有这个名字的房间”。 如果我尝试res.send或res.json它将我redirect到显示上面的消息的空白页面。 我不喜欢也做一个url查询。 有没有办法做到这一点? 谢谢

$('#btn2').click(function(){ $.ajax({ type: "POST", url: '/joinRoom', data: $('#roomJoin').val(), dataType: 'json', success: function (response) { console.log(response); } }); }) 

app.js

 app.post('/joinRoom', checkAuthentication,function(req,res){ console.log(req.body); User.findOne({ createRoom:req.body.roomJoin }, function(err,obj){ if(err){ console.log(err.code); } else if(!obj) { res.redirect('index_connected.html'); } else if(obj){ res.redirect('board.html'); } }); }) 

url查询中发送消息将是实现此目的的最简单方法。 如果你不想要他们,你可以尝试下面的select。

从服务器发送一个cookie,并在页面加载,检查你是否有cookie。 如果有,请显示一条消息并删除该Cookie。 如果不跳过它。

你可以这样做

 app.post('/joinRoom', checkAuthentication,function(req,res){ console.log(req.body); User.findOne({ createRoom:req.body.roomJoin }, function(err,obj){ if(err){ console.log(err.code); } else if(!obj) { res.redirect("index_connected.html/?message=there isn't a room with this name"); } else if(obj){ res.redirect('board.html'); } }); })