首页 > 解决方案 > 使用 ajax 重新加载部分页面

问题描述

我正在使用 express 来显示正在运行的进程列表。我希望他们每隔几秒钟重新加载一次,以删除已完成的内容并添加新内容。

我为此使用ajax:

我的 layout.pug(删节)

div(class="processes")
    for process in processes
         div(class="process")=process.name

  script.
    setInterval(() => {
      $.ajax({
        url: "/processes/running",
        type: "GET",
        success: function(response, status, http) {
          if (response) {
              processes = $('.processes')[0]
              html = ""
              for(process of response){
                html +='<div class="process">'+process.name+'</div>'
              }
              $(processes).html(html)
          }
        }
      });
    }, 3000)

而对应的路线就是

app.get('/processes/running', function(req, res){
    res.send(processes)
})

processes我用来跟踪它们的数组在哪里。

这工作正常。但是,我不喜欢代码重复。我基本上必须在我的代码中构建列表/表格两次。如果我改变一些东西,我必须在两个地方都改变它......

那么,有没有更好的方法来实现这一点?

标签: ajaxexpresspug

解决方案


避免重复的解决方案就是不初始化你的 div 内部

div(class="processes")


  script.
    setInterval(() => {
      $.ajax({
        url: "/processes/running",
        type: "GET",
        success: function(response, status, http) {
          if (response) {
              processes = $('.processes')[0]
              html = ""
              for(process of response){
                html +='<div class="process">'+process.name+'</div>'
              }
              $(processes).html(html)
          }
        }
      });
    }, 3000)

div 将在第一次调用后填充。

如果您已经有数据,您可以将“html 创建部分”(if(response)块)放在一个函数中,并在调用 setInterval 之前调用它,并像现在一样在响应中调用它。这将允许您在一个地方拥有定义数组的代码

如果您还没有数据,我建议在 div 中显示一条消息,例如“还没有数据,请稍候”


推荐阅读