我使用 MongoDB 和 NodeJS(带有 Express Framework)。
我实际上做了什么:
- 抓取 MongoDb 中的一些数据
- 渲染此数据。
我想做的事情:
过滤特定项目。
过滤后的结果都是正确的,但我的问题是页面会渲染两次。
如何防止这种情况发生?
我有一个主上下文根,实际上看起来像这样:
app.get('/main', auth, function(req, res) {
getItems(req, res, function(results) {
renderResults(req, res, results);
});
});
这是我的渲染结果函数:
function renderResults(req, res, results) {
console.log("In Rendermethode arrived:");
console.log(results.items);
res.render('pages/main', {
offerings: results.items,
ownUser: {
id: req.session.user || ""
},
filterObj: {
isActivated: typeof results.filterObj !== 'undefined',
filterFor: typeof results.filterObj !== 'undefined' ? results.filterObj.filter : "",
filterText: typeof results.filterObj !== 'undefined' ? results.filterObj.filterText : ""
}
});
}
我所做的是在前端发送请求:
$("button.doSearch").on("click", function(e) {
var dFilter = $("div.filterDropdown button").attr("value") || "",
dFilterText = $("input.searchterm").val() || "";
$.post("/search", {
filter: dFilter,
filterText: dFilterText
},
function(data, status) {
});
});
这是搜索的后端片段:
app.post('/search', auth, function(req, res) {
console.log("Filterrequest received.");
getItems(req, res, function(results) {
renderResults(req, res);
});
});
最佳答案
我认为您正在渲染同一 View 两次,因为您在 get 和 post 请求中都调用了 renderResults 函数
问题:
您发出的第一个 HTTP 请求是对 /main
url 的 GET 请求,express 会处理它并呈现 pages/main
View
第二个请求是发送到 /search
url 的 xhr post,express 将处理它并呈现相同的 View pages/main
(整个页面)
将整个页面渲染到 AJAX 对象是没有意义的,相反,您可以渲染 JSON 对象并使用 native javascript 或 JQuery 更新页面
解决方案:
根据请求类型呈现不同类型的数据(xhr 或不是):
function renderResults(req, res, results) {
var result = {
offerings: results.items,
ownUser: {
id: req.session.user || ""
},
filterObj: {
isActivated: typeof results.filterObj !== 'undefined',
filterFor: typeof results.filterObj !== 'undefined' ? results.filterObj.filter : "",
filterText: typeof results.filterObj !== 'undefined' ? results.filterObj.filterText : ""
}
};
if (!req.xhr) {
return res.render('pages/main', result);
}
res.json(result);
}
关于node.js - NodeJS - 在 res.render() 之后快速重新加载页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47226219/