使用Express提交发帖请求后如何保持在同一页面上? [英] How to stay at the same page after submitting post request with Express?
问题描述
我知道这可能是一个简单的问题,但我只是没有找到想要的解决方案.我写快递的邮政路线.像这样:
I know this might be a simple question but I just didn't find the solution I want. I write a post route with express. like this:
app.post('/search', function(req, res){
// Some code to get data from req and save data to db
// Then want to stay current page.
});
我的html:
<form action="/search" method="post">
<input value="name" name="marker[name]">
<input value="address" name="marker[address]">
<input value="rating" name="marker[rating]">
<button id="favo-button" type="submit">
Submit
</button>
</form>
当用户单击提交"按钮时,通过req发送到发布路径的数据,然后插入到db中.然后,我希望页面不要直接指向任何地方,而是保持当前页面.我尝试了一些方法,但处理得不太好.我尝试过的:
When user click submit button, the data sent through req to the post route, and there insert to db. Then I want the page not direct to anywhere but stay current page. I tried some ways but not handle it very well. what I tried:
- 在路线上
res.render('/search');
这将使页面以相同的视图重新渲染,但是由于重新渲染,页面将闪烁.
this makes the page re-render with the same view, but the page will flash because of the re-render.
- 对路线中的资源不做任何事情,因此页面加载圈子将永远不会停止.
app.post('/search', function(req, res){
var data = req.body.marker;
// some code insert data to db
// then do nothing to res. The page will stay but keep loading.
});
有什么办法可以使res
什么都不做并停留,而同时又不保持页面加载?
Is there a way to just do nothing to res
and stay, meanwhile not keep the page loading?
推荐答案
有两种方法可以做到这一点.
There are two ways to do this.
- 返回
204 No Content
响应. (app.post('/search', (req, res) => res.status(204).send());
) - 使用JavaScript(例如Ajax,例如,使用 XMLHttpRequest ),而不是提交表单
- Return a
204 No Content
response. (app.post('/search', (req, res) => res.status(204).send());
) - Make the request with JavaScript (i.e. Ajax, e.g. with XMLHttpRequest) instead of submitting the form
(您也可以将表单提交到隐藏的iframe中,但这只是一个丑陋的hack).
(You could also submit the form to a hidden iframe, but that's just an ugly hack).
这篇关于使用Express提交发帖请求后如何保持在同一页面上?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!