How to create a ajax POST with node JS?

大城市里の小女人 提交于 2019-12-24 21:30:07

问题


I am not sure how to use an ajax POST to POST from a Jade Page to Node JS. If someone can provide an example or tell me what I am missing from the script I have, please let me know.

This is the script file:

  //Add friends
    $('.addContact').click(function() {
    $.post('/addContact',
       {friendRequest: $(this).data('user')});

    if($(this).html!=='Contact Requested') {
        return $(this).html('Contact Requested');
    }
    });  

The url I have for a POST on my app.js file is:

app.post('/addContact', user.addContactPost);

I am trying to post true for a click event on the button Add Contact and change it to Contact Requested if the data in the db is shown as true.

This is the jade file:

extends layout
block content   
    div
    legend Search Results
    div#userResults
    for user in ufirstName 
        a(href='/user/#{user.id}')
            p #{user.firstName} #{user.lastName}
        button.addContact Add Contact

The route file is this:

    exports.addContactPost = function(req, res, err) {
    User.findByIdAndUpdate(req.signedCookies.userid, {
                $push: {friendRequest: req.body.friendRequest}
            }, function(err) {
                if(err) {
                    console.log("post2");
                    return console.log('error');
                    //return res.render('addContactError', {title: 'Weblio'}); 

                } 

                else {
                    console.log('postsuccess');
                    //alert('Contact added');
                    res.json({response: true});

                }

            });
};

回答1:


If you are posting AJAX request, then you are expecting from JS on client-side to get some response, and react to this response accordingly. If it would be separate request to another page - then probably rendering whole page - would be actual option.

But as you just need to get response from server and then update your front-end without reloading based on response, then you need to response from server on this POST request with some JSON. And then on client-side, do some templating, use jQuery or some templating libraries on client side for it.




回答2:


Everything looks good I just think the $.post code is a little off. This might fix your problem.

 $('.addContact').click(function() {
    $.post('/addContact', { addContact : true }, function(data){
        console.log('posting...');
        $('.addContact').html(data);
    });

    ...
});

The object I added to the $.post is what is going to be sent to the server. The function you specified at the end is your callback. It's going to be called when the function returns. I think that may have been some of your confusion.

Your node route should look something like this

exports.addContactPost = function(req, res, err) {
    User.findByIdAndUpdate(req.signedCookies.userid,{
            addContact: req.body.addContact
        }, function(err) {
            if(err) {
                console.log("post2");
                res.render('addContactError', {title: 'Weblio'}); 
            } 
            //assuming express return a json object to update your button
            res.json({ response  : true });
        });
};


来源:https://stackoverflow.com/questions/17714202/how-to-create-a-ajax-post-with-node-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!