gpt4 book ai didi

node.js - 使用 EJS 和 Express 刷新页面部分

转载 作者:行者123 更新时间:2023-12-02 04:14:58 26 4
gpt4 key购买 nike

我有一个复选框,当按下该复选框时,将调用执行 GET 请求的函数。根据选择,我想在同一页面上显示额外的复选框。目前这是我到目前为止的代码:

客户端

function selectedHouse(house)
{
if(house.checked){
$.get('/', {data: house.value});
}
}

服务器端

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;
};

页面第一次加载时,会加载正确的标题、导航和房屋。当该函数在客户端执行时,我取回房屋的相关房间,并尝试填充我在 View 上显示的 roomsForHouse 变量。

问题是 View 不渲染 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
...
});
});

客户端

一旦用户选择了房子,就使用 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);
});
}
}

这更多的是伪代码,但应该会让您走上正确的轨道。

关于node.js - 使用 EJS 和 Express 刷新页面部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34354975/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com