简体   繁体   中英

How to grab data from a js script in Jade for Node.js?

I am trying to grab client side info that was queried already for the server side of a POST. Currently working on a friend button that when clicked POST's to a route file, but I am not sure how to grab the user.id associated with it and send it back to Node.JS.

Here is the jade file includes a for loop that has the user.id of each person.

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

Here is the route file: I am trying to figure out what to put on the other side of the friendRequest:

exports.addContactPost = function(req, res, err) {
    User.findByIdAndUpdate(req.signedCookies.userid,{
                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');

                }

            });
};

This is the script file trying to do the magic:

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

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

Try this:

button.addContact(onclick="addContact('#{user.id}')") Add Contact

JS:

function addContact(userId){
    $.post('/addContact', { friendRequest: userId }, function(result){
        // use result
    });
}

I would store the ID in the Add Contact link:

button.addContact(data-user=user.id) Add Contact

Amnd get it in the handler

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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