【问题标题】:Reload parts of page with ajax使用 ajax 重新加载部分页面
【发布时间】:2021-08-28 10:34:11
【问题描述】:

我正在使用 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 是我用来跟踪它们的数组。

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

那么,有没有更好的方法来做到这一点?

【问题讨论】:

    标签: ajax express pug


    【解决方案1】:

    避免重复的解决方案就是不初始化 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 中显示一条消息,例如“还没有数据,请稍候”

    【讨论】:

    • 是的,我想这是最好的解决方案,但我希望有更好的方法;D
    猜你喜欢
    • 1970-01-01
    • 2019-08-23
    • 1970-01-01
    • 2010-09-08
    • 1970-01-01
    • 1970-01-01
    • 2014-12-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多