【问题标题】:How read response from a post request in jquery?如何在 jquery 中读取 post 请求的响应?
【发布时间】:2019-01-23 23:21:15
【问题描述】:

我在 node.js 中编写了一个向我的客户端发送邮件的方法,如下所示:-

app.post('/sendemail',(req, res) => {
  const output = `
    <p>You have a new contact request</p>
    <h3>Contact Details</h3>
    <ul>  ;
      <li>Name: ${req.body.name}</li>
      <li>Email: ${req.body.email}</li>
      <li>Phone: ${req.body.phone}</li>
    </ul>
    <h3>Message</h3>
    <p>${req.body.message}</p>
  `;

  // create reusable transporter object using the default SMTP transport
  let transporter = nodemailer.createTransport({service: 'gmail ',

auth: {
user: 'atul.11192@gmail.com',
pass: 'xxxxxxx'
},
    tls:{
      rejectUnauthorized:false
}
  });

  // setup email data with unicode symbols
  let mailOptions = {
      from: '"Enquiry from datadock" <atul.11192@gmail.com>', // sender address
      to: 'atul.11192@gmail.com', // list of receivers
      subject: 'Datadock Enquiry ', // Subject line
      text: 'Hello world?', // plain text body
      html: output // html body
  };

  // send mail with defined transport object
  transporter.sendMail(mailOptions, (error, info) => {
      if (error) {
          res.send('error');
      }
        res.redirect('home.ejs',{message:"message sent"});
  });
  });

现在我想编写一个 jquery 函数来读取我从这个方法发送的响应并显示一个模式,我该如何编写这段代码?由于路线很多,我必须使用 j 查询,因为无法使用 javascript

【问题讨论】:

    标签: jquery json node.js


    【解决方案1】:

    因为您要重定向到新路由器,所以您需要在会话中设置要发送到前端的数据。但是,您可以通过向同一路由器发送响应来避免这种情况。要实现这一点:

    jQuery('button').on('click', function(event) {
        event.preventDefault();
        jQuery.ajax({
            url: '/sendemail',
            dataType: 'json',
            success: function(data) {
                alert(data.message);
                jQuery('.yourModal').text(data.message).show();
                /*setTimeout(function() {
                //window.location.href = data.yourRedirectUrl;
                }, 1000);*/
            }
        });
    });
    

    然后你需要替换以下内容:

    res.redirect('home.ejs',{message:"message sent"})
    

    有了这个:

    res.end(JSON.stringify({message:"message sent", yourRedirectUrl: '/home'});
    

    如果还需要重定向,可以取消注释我在ajax脚本中添加的setTimeout函数。

    编辑:或者,您可以将重定向设置为具有哈希

    res.redirect('home#mailsent',{message:"message sent"})
    

    并将以下内容放在 home.ejs 上:

    jQuery(document).on(‘load’, function(){
        if(window.location.hash == ‘mailsent’) {
            // Do stuff with your modal here
        }
    });
    

    【讨论】:

    • 我需要让它成为一个按钮点击事件,否则它会在没有点击按钮事件的情况下单独工作?
    • 我已经编辑了我的答案。对于第一个解决方案,是的。对于添加哈希的替代解决方案,不。我建议亲自使用替代方案,只需在要将用户重定向到的 url 末尾添加一个哈希。这样,当他们使用该哈希登陆主页时,您就可以显示您的模式。
    猜你喜欢
    • 2013-06-19
    • 2013-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多