【问题标题】:How to render EJS at anchor如何在锚点处渲染 EJS
【发布时间】:2019-11-04 17:41:44
【问题描述】:

我想做一些事情(也许有一种我没有看到的更简单的方法)但基本上我想要做的是有一个带有 Mailchimp 注册表单的 EJS 文件,然后当注册被填满时它重定向到同一个 EJS 文件,但这次使用了一个将文本添加到 HTML 的变量。

基本上,当用户输入电子邮件时,我们会将他重定向到同一部分,但这次它添加了带有文本“谢谢,我们已经收到您的电子邮件,我们会尽快与您联系”的 ap 标签,这里是我的方法:

app.post('/', (req, res) => {
  mailchimp.post('/lists/' + process.env.MAILCHIMP_LIST + '/members', {
      email_address: req.body.email,
      status: 'subscribed'
    }, (err) => {
    if(err){
      console.log(err.title);
      if(err.title == 'Member Exists'){
        res.redirect('/#signup', {
          Status: "Thank you, we've got your email, we'll get in touch with you soon"
        })
      }else{
        res.redirect('/#signup', {
          Status: "We're having problems signing you up, if the problem persists send an email to hello@hibuddie.com"
        })
      }
    }
  });
  res.redirect('/#signup', {
    Status: "Thank you, we've got your email, we'll get in touch with you soon"
  });
});

但是,当我尝试执行此操作时,我的控制台上出现错误:

express deprecated res.redirect(url, status): Use res.redirect(status, url) instead app.js:45:7

我知道重定向可能不适用于 EJS,但我不知道该怎么做,所以它将用户重定向到具有特定 ID 的相同 EJS 文件,在这种情况下说 /#signup。

请原谅我糟糕的代码,我要开始了,哈哈。

【问题讨论】:

    标签: html node.js express ejs mailchimp


    【解决方案1】:

    你可以通过两种方式做到这一点:

    您可以使用rendering 代替redirecting,并将变量添加到渲染函数中。

    // pass a local variable to the view
    res.render('user', { name: 'Tobi' }, function (err, html) {
      // ...
    })
    

    并处理视图文件中的变量。 您还可以发送一个 anchor 名称作为变量并添加一些 javascript 来处理它。喜欢:

    res.render('user', { anchor: 'signup' }, function (err, html) { ... });
    

    并在模板文件中添加一些javascript,

    window.onload = function (event) {
        window.location.hash = "#{{anchor}}";
    };
    

    或者,如果您使用Ajax 调用来访问api,您可以返回类似的状态,

    res.json({
        success: true,//or false
        data: {
            Status: "some text"
        }
    })
    

    并在前端使用 Javascript 进行处理。

    【讨论】:

    • 如果我使用渲染,如何将用户发送到特定部分,例如,我有一个 id 为“注册”的部分,如何渲染“索引”文件并在渲染后“自动向下滚动”到注册部分?谢谢你:)
    • 编辑了答案以包含此内容。
    猜你喜欢
    • 1970-01-01
    • 2018-10-26
    • 2018-01-12
    • 1970-01-01
    • 2018-12-26
    • 1970-01-01
    • 2018-12-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多