使用jQuery Ajax和NodeJS:获取返回的值

时间:2015-10-20 18:42:06

标签: jquery ajax node.js

我正在尝试将returned值从Node发送到客户端,但我遇到了问题。为什么我看不到用户名?

app.js

var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

var routes = require('./routes/index');
var users = require('./routes/users');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.post('/login', function(req,res) {
  var returned = req.body.username;
  console.log(returned); // returns undefined, but it works if I remove jquery post (normal post works), so I think there's a problem with req.body.username since it returns undefined.
});

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
  app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
      message: err.message,
      error: err
    });
  });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
  res.status(err.status || 500);
  res.render('error', {
    message: err.message,
    error: {}
  });
});

module.exports = app;

的Javascript

$(document).ready(function(e) {
   $(".submit").click(function(e) {
       e.preventDefault();
       $.post(
           "/login", function(returned) {
               $('.result').html(returned);
           }
       )
   });
});

login.jade

doctype html
html(lang='en')
    head
    body
        form(method='post', action='login')
            input(type='text', name="username")
            input(type='submit', class="submit")
        div(class="result")
    script(src="https://code.jquery.com/jquery-2.1.4.js")
    script(src="javascripts/index.js")

1 个答案:

答案 0 :(得分:1)

在您的$ .post中,您没有传递用户名,因此undefined是您应该在服务器端预期的内容。传递数据只需稍作改动:

   $.post(
       "/login", $('form').serialize() function(returned) {
           $('.result').html(returned);
       }
   )

我建议使用表单的提交事件,使代码更容易(主观)。

doctype html
html(lang='en')
    head
    body
        form(id='myform', method='post', action='login')
            input(type='text', name="username")
            input(type='submit', class="submit")
        div(class="result")
    script(src="https://code.jquery.com/jquery-2.1.4.js")
    script(src="javascripts/index.js")
$(document).ready(function(e) {
   $("#myform").submit(function(e) {
       e.preventDefault();
       $.post(
           "/login", $(this).serialize(), function(returned) {
               $('.result').html(returned);
           }
       )
   });
});

它还避免了在没有点击事件触发的情况下提交表单错误的可能性。