使用 EJS 和 Express 刷新页面部分

Refresh section of a page using EJS and Express

我有一个复选框,当按下它时调用一个执行 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;
};

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

问题是视图不呈现 roomsForHouse 变量。因此,GET 请求在页面加载后调用,第二次在函数执行时调用。这能实现吗?

res.render 无法重新渲染视图,第二次刷新页面需要使用 javascript 替换 html。这不是很好的解决方案

$.get("/",function(html){

 document.open();

document.write(html);

document.close();

});

为了更好,您应该使用另一个路由器来呈现您想要更改的DOM

有点复杂。为此,您需要使用 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);  
      });
   }
}

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