weixin_33694172 2012-09-28 18:41 采纳率: 0%
浏览 46

expressJS中的AJAX调用

I can't seem to get the AJAX call correct. There have been other QA that deal with the $.ajax() function but I'm trying to solve this with $.post().

When the form button is clicked the javascript at the head is executed, which includes a $.post(). The url /login is routed through and passed to loginPost function. There a response is determined and sent back to the javascript (right?). Instead, webpage renders the response (pass || fail).

Why isn't the response from the AJAX call being sent back to get processed?

This is a simple example that I am working with to get me better acquainted to how AJAX in expressJS and jQuery work. Any Help is greatly appreciated!

--views/login.jade

script(src='/_js/jquery-1.8.2.min.js')
script
  $(document).ready(function(req, res) {
    $('#login').submit(function() {
    var formData = $(this).serialize();
    console.log(formData);
    $.post('/login', formdata, processData).error('ouch');

    function processData(data, status) {
      console.log(status);
      console.log(data);
      if (data == 'pass') {
        $('#content').html('<p>You have successfully loggin in!</p>');
      } else {
        if (! $('#fail').length) {
          $('#formFrame').prepend('<p id="fail">Incorrect login information. Please try again)</p>');
        }
      }
    } //end processData
  }); //end submit
}); //end ready

div.main
h1= title
div#formFrame
  form(id='login', action='/login', method='POST')
p
  label(for='username') Username:
  input(id='username', type='text', name='username')
p
  label(for='password') Password:
  input(id='password', type='password', name='password')
p
  input(id='button', type='submit', name='button', value='Submit')

--routes/index.js

app.post('/login', loginPost);

--routes/loginPost

module.exports.loginPost = function(req, res) {
    var password = 'admin'
      , username = 'user'
      , data = req.body;

    if (data.username == username && data.password == password) {
      res.send('pass');
    } else {
      res.send('fail');
    }
};
  • 写回答

1条回答 默认 最新

  • weixin_33716557 2012-09-28 19:17
    关注

    You still have to stop the <form> from submitting via its default action, which can be done with event.preventDefault():

    $('#login').submit(function(evt) {
      evt.preventDefault();
      // ...
    });
    

    Otherwise, the <form> will redirect the page to its action (or back to the current address if no action was given), interrupting the $.post request.

    评论

报告相同问题?

悬赏问题

  • ¥15 用三极管设计—个共射极放大电路
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示