Getting AJAX to work with node.js

时间:2016-07-11 22:42:17

标签: javascript ajax node.js

I have this POST request for a registration page. It checks to see if a username is already being used by another user:

router.post ('/register', function(req, res) {
User.findOne({username: req.body.username}, function(err, existingUser) {
    if(existingUser) {
        req.flash('errors1', req.body.username + ' already exists.');
        return res.redirect('/register');
    }
//some more code down here if the username is unique

And here is the form (I'm using EJS):

<form method="POST" action="/register">
    <% if (errors1.length > 0) { %>
        <div class='form-group has-error'>
            <label for="username">Stock Ticker</label>
            <input type="text" name="username" class="form-control" id="username"/>
            <span class="help-block"><%= errors1 %></span>
        </div>

Basically, if the username entered is not unique, a message will appear just below the form telling the user that the username cannot be used. But this message only shows up after a user has hit the SUBMIT button.

How can I incorporate AJAX into this? I've never really used AJAX before, and have been going through the documentation and watching tutorials, but I just can't wrap my head around how I could incorporate AJAX into this piece of code.

1 个答案:

答案 0 :(得分:1)

你应该创建新的api来进行检查并在输入控件 失去焦点时触发此请求,可能代码如下所示:

server.js:

router.post ('/check_username', function(req, res) {
    //CODE:check your username 
})

html

<div class='form-group has-error'>
        <label for="username">Stock Ticker</label>
        <input type="text" name="username" class="form-control" id="username"/>
        <span class="help-block"><%= errors1 %></span>
</div>

js(Jquery):

$("#username").focusout(function(){
        var value = $("#username").val();
        //CODE:send the request and display result;
        $.post('/check_username',{username:value},function(data){
        //CODE:handle result
        })
    });