7

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

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

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"
    // });
});

如果有人有过这项工作的经验,您的意见将不胜感激。

4

3 回答 3

4

I'm not exactly sure what you're after, but if it's updating the page with the results of an AJAX call (which does not refresh or otherwise reload the page) then you'll have to use client-side JavaScript. jQuery's load() or post() should be able to handle that.

Alternatively, if you are not using AJAX but instead performing a normal form submit, you have a couple of options. One, you can keep your redirect in and use Express/Connect's Sessions system to determine what is used for the get request, or two you can replace the redirect with another res.render of the index.jade page and include the variable you want to change.

It should be understood that after either of these takes place, node.js relinquishes control of the web page to the browser, unless you specifically set up architecture for communication. There are currently no controls in node.js to force updates or page changes down to the client. Except via socket connections or unless otherwise polled by the client itself (such as in the first example involving jQuery).

于 2011-03-15T19:58:09.133 回答
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
  });
});
于 2013-04-19T01:06:27.463 回答
0

你可以使用类似下面的东西,或者如果你想使用 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
});
于 2011-09-13T13:48:57.323 回答