Node JS Form Sumit使用Ajax

时间:2015-11-02 10:09:45

标签: ajax node.js

我是Node JS的新手,我想使用ajax提交一个表单,就像我们在PHP / CakePHP中所做的一样,但在这里我遇到了一个问题。

HTMl代码

With Java 8 DateTime / LocalDateTime :

private static String getDate(int month, int year) {        
    Month monthObj = Month.of(month);       
    LocalDate date = LocalDate.of(year, month, monthObj.maxLength());
    return date.format(DateTimeFormatter.ofPattern("MM/dd/yyyy", Locale.US));
}

我的AJAX代码是

<form role="form" action="javascript:;" id="myform">
        <div class="form-group">
          <label for="name">Name:</label>
          <input type="text" class="form-control" id="name" name="name" placeholder="Enter Name">
        </div>
        <div class="form-group">
          <label for="email">Email:</label>
          <input type="email" class="form-control" id="email" name="email" placeholder="Enter email">
        </div>
        <button type="submit" class="btn btn-default" id="enter">Submit</button>
      </form>

app.js代码

$('.btn').click(function(e){ 
          e.preventDefault();
          var data = $('#myform').serialize();
          $.ajax({ 
              url: '/ajax',
              type: 'POST',
              cache: false, 
              data: JSON.stringify(data),
              contentType: 'application/json',
              success: function(data) {
                          console.log(data);
                          console.log(JSON.stringify(data));
                        },
              error: function(jqXHR, textStatus, err){
                   alert('text status '+textStatus+', err '+err);
               }
            })
          });            

但是当我提交此表单时,它会在节点控制台中生成错误,如

app.post('/ajax', bodyParser(), function (req, res){

  var obj = {};
  console.log('body: ' + JSON.stringify(req.body));

  var input = JSON.stringify(req.body);
  var data = {

      name    : input.name,
      email   : input.email
  };

  var query = db.query("INSERT INTO users set ?",data, function(err, rows){
  console.log(query.sql);
      if (err)
          console.log("Error inserting : %s ",err );
         res.send({'success' : true, 'message' : 'Added Successfully'});
  });


});

1 个答案:

答案 0 :(得分:1)

我认为,我并非百分之百确定,您应该将var data = $('#myform').serialize();替换为var data = $('#myform').serializeArray();