Mih*_*goe 2 ejs node.js express
我有一个复选框,当按下该复选框时,将调用执行 GET 请求的函数。根据选择,我想在同一页面上显示额外的复选框。目前这是我到目前为止的代码:
客户端
function selectedHouse(house)
{
if(house.checked){
$.get('/', {data: house.value});
}
}
Run Code Online (Sandbox Code Playgroud)
服务器端
var routing = function (nav, houses) {
router.route('/')
.get(function (req, res) {
var rooms = [];
rooms = getRooms(req.query.data);
console.log(rooms);
res.render('index', {
title: 'Independent cleaner',
nav: nav,
houses: houses,
roomsForHouse: rooms
});
});
return router;
};
Run Code Online (Sandbox Code Playgroud)
页面第一次加载时,会加载正确的标题、导航和房屋。当该函数在客户端执行时,我取回房屋的相关房间,并尝试填充我在视图上显示的 roomsForHouse 变量。
问题是视图不渲染 roomsForHouse 变量。因此,一旦页面加载,就会调用 GET 请求,并在函数执行时再次调用。这能实现吗?
这有点复杂。为此,您需要使用 ajax。EJS 是服务器端模板(当您使用它们时),因此您需要使用 jQuery 进行调用并更新已呈现的页面。
服务器 您的服务器将需要一个传递 JSON 数据的路由。现在您正在渲染整个页面。所以:
app.get('/rooms/:id', function (req, res) {
// Get the house info from database using the id as req.params.id
...
// Return the data
res.json({
rooms: 2
...
});
});
Run Code Online (Sandbox Code Playgroud)
客户
一旦用户选择了房子,就使用 jQuery 调用您的 json 路由。
function selectedHouse(house)
{
if(house.checked){
// Pass some identifier to use for your database
$.ajax({
type: 'GET',
url: '/rooms/' + house.id,
success: function(data) {
// Update the element - easiet is to use EJS to make sure each house has an id/class with the id in it
// Given an ID of 2 this says find the div with class house_2 and updates its div with class room to the number of rooms
$('.house_' + house.id + ' .rooms').text(data.rooms);
});
}
}
Run Code Online (Sandbox Code Playgroud)
这更多是伪代码,但应该让您走上正确的轨道。