【问题标题】:How do I update A Jade Template form an ajax post?如何从 ajax 帖子中更新 Jade 模板?
【发布时间】:2011-07-13 00:55:29
【问题描述】:

我已经设置了一个基本的 node.js 网络应用,使用 express 和默认的视图引擎 jam。

当用户第一次加载页面时,会发生以下情况

app.get('/', function(req, res){
    res.render('index', {
        title: 'Test',
        mode: "user"
    });
});

我无法解决的是如何更改我最初从 ajax 调用传递到玉模板的参数。

app.post('/', function(req, res){
    console.log(req.body.list);
    res.redirect('back');
    // I imagine the code needs to go here and look somewhat like the following
    // 
    // res.?update-view({
    //  mode: "admin"
    // });
});

如果有人对此工作有经验,我们将不胜感激。

【问题讨论】:

  • 您到底想达到什么目的?我看到的唯一解决方案是使用客户端代码更新 gui(使用您的快速后处理程序呈现的数据)

标签: node.js pug express


【解决方案1】:

假设你想显示同一个页面,用其他“模式”

// set the page title for all requests
app.locals({ title: 'Test' });

// GET request
app.get('/', function(req, res){
  res.render('index', {
    // displays the default "user" mode
    mode: 'user'
  });
});

// when POST is submited
app.post('/', function(req, res){
  // this is the param given by the user
  console.log(req.body.list);

  // now render the same page
  res.render('index', {
    // with mode set to the the given parameter
    mode: req.body.list
  });
});

【讨论】:

    【解决方案2】:

    你可以使用类似下面的东西,或者如果你想使用 AJAX 调用,只要有响应就使用 jQuery ajax

    客户

    script(type="text/javascript")
      $(document).ready(function(){
        //...AJAX here....
        var newValue = #{value} + 10;
      });
    

    服务器

    app.get('/ajax', function(req, res){
     //This is where your code and response go
    });
    

    【讨论】:

      【解决方案3】:

      我不完全确定您的目标是什么,但如果它使用 AJAX 调用的结果更新页面(不会刷新或重新加载页面),那么您将不得不使用客户端 JavaScript . jQuery 的 load()post() 应该能够处理。

      或者,如果您不使用 AJAX 而是执行普通的表单提交,那么您有几个选择。一,您可以保留您的重定向并使用 Express/Connect 的 Sessions 系统来确定用于获取请求的内容,或者二您可以将重定向替换为 index.jade 页面的另一个 res.render 并包含您的变量想要改变。

      应该理解,在其中任何一个发生之后,node.js 都会将网页的控制权交给浏览器,除非您专门设置了通信架构。 node.js 目前没有控件来强制更新或页面更改到客户端。除非通过套接字连接或除非客户端本身轮询(例如在第一个涉及 jQuery 的示例中)。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2010-11-12
        • 2016-02-18
        • 1970-01-01
        • 2021-10-03
        • 1970-01-01
        • 2013-03-20
        • 1970-01-01
        相关资源
        最近更新 更多