简体   繁体   English

使用AJAX在nodeJS Express MongoDB中发送post请求

[英]Using AJAX to send post request in nodeJS Express MongoDB

I have got a newsletter section on my website with two fields, name and email. 我的网站上有一个时事通讯部分,有两个字段,名称和电子邮件。 What I am after is that the user can fill the form and send it, saving the data in MongoDB and not reloading or redirecting the page, I am not interested in the result, all I want is to keep that data so in future, I can start sending newsletters, although refreshing just the newsletter section would be nice. 我所追求的是用户可以填写表格并发送,保存MongoDB中的数据,而不是重新加载或重定向页面,我对结果不感兴趣,我想要的是将来保存这些数据,我可以开始发送新闻通讯,虽然只刷新通讯部分会很好。

Bonus: The form is in the partial footer, so the form can be sent from any route in the website. 奖励:表单位于部分页脚中,因此表单可以从网站的任何路径发送。

These are my efforts: 这些是我的努力:

schema: 模式:

var UserSchema = new mongoose.Schema({
    name: {
        type: String,  
        required: true
    },
    email: {
        type: String, 
        unique: true, 
        required: true, 
        lowercase: true
    }
});

Server side: 服务器端:

//newsletter post
router.post("/", function(req, res){
    Newsletter.create(req.body.newsletter, function(err, newsletter) {
        if (err){
            console.log(err);
        } else {
            req.flash("success", "You have been successfully added to our newsletter! ");
            console.log(newsletter);
        }
    });
});

Footer partial: 页脚部分:

<form id="newsletterForm" action="/" method="POST">
  <input id="newsletterName" type="text" name="newsletter[name]">
  <input id="newsletterEmail" type="email" name="newsletter[email]">
  <button id="submit" type="submit">Suscríbete</button>
</form>

jQuery jQuery的

// Using Ajax to send a form without refreshing page
    $('#submit').on('submit', function(e){
        e.preventDefault(); 
        $.ajax({
            url: '/',
            method: 'POST',
            contentType: 'application/json',
            success: function(html) {
            alert('data sent!');
            }
        });
        //return false; 
    });

At the moment is saving the data in MongoDB but after submiting the form the reload button of the browser is forever moving, no flash it's being shown and the form stays filled, however, it is console.logging the result. 目前正在将数据保存在MongoDB中,但在提交表单后,浏览器的重新加载按钮将永远移动,没有显示闪存并且表单保持填充状态,但是,它是console.logging结果。

Any help or pointing in a right direction would be great! 任何帮助或指向正确的方向都会很棒! thanks. 谢谢。

send a response 200 from expressjs server 从expressjs服务器发送响应200

router.post("/", function(req, res){
    Newsletter.create(req.body.newsletter, function(err, newsletter) {
        if (err){
            console.log(err);
            res.send(err)
        } else {
            res.status(200).json({ message: 'success' });
            console.log(newsletter);
        }
    });
});


$('#submit').on('submit', function(e){
    e.preventDefault(); 
    $.ajax({
        url: '/',
        method: 'POST',
        contentType: 'application/json',
        success: function() {
          alert('data sent!');
          return false
        }
    });
    //return false; 
});

you are missing 2 things:- 1) you are not sending any response from the route, so it will not end it will keep waiting and scrolling, 你缺少两件事: - 1)你没有从路线发送任何回应,所以它不会结束它会继续等待和滚动,

router.post("/", function(req, res){
Newsletter.create(req.body.newsletter, function(err, newsletter) {
    if (err){
        console.log(err);
        res.status(200).json({ error: 'failed' });
    } else {
        res.status(200).json({ message: 'success' });
        console.log(newsletter);
    }
});
});

2) In ajax call, you should return false at end, so it will prevent page from reloading as it will not post form in page, so do 2)在ajax调用中,你应该在结尾返回false,因此它会阻止页面重新加载,因为它不会在页面中发布表单,所以

$('#submit').on('submit', function(e){
    e.preventDefault(); 
    $.ajax({
        url: '/',
        method: 'POST',
        contentType: 'application/json',
        success: function(html) {
          alert('data sent!');
          //return false
        }
    });
    return false; 
});

Now, it will not reload the page. 现在,它不会重新加载页面。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM