簡體   English   中英

如何從 jquery 中的 post 請求中讀取響應?

[英]How read response from a post request in jquery?

我已經編寫了一個方法,可以像這樣在 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('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
    }
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM