简体   繁体   中英

How do I prevent redirect after POSTing form data in express.js?

I've seen in other posts how to prevent a redirect on an AJAX call by returning false in the submit override method, but this doesn't work in express. I can't figure out how to present the redirect after submitting data. The following code executes properly, but redirects to init.

app.js

 app.post('/init', routes.init(db));

routes/index.js

exports.init = function(db){
  return function(req, res) {
    var name = req.body.name;
    var track = req.body.track;

    var collection = db.get('configs');

    collection.insert({
      "name": name,
      "track": track
    }, function (err, doc) {
      if (err) {
        res.send("Error occurred adding config to db");
      }
      else {
        res.send(200);
      }
    });
  };
};

admin.jade

  script(type='text/javascript').
      $(document).ready(function() {
        $('#formInit').submit(function() {
          $.post('/init', 
            { name : $(this).name.value,
              track : $(this).track.value 
            }   
          );  
          return false;
        }); 
     });

    ....

    block content
      #control-panel

        form#formInit(name='init', action="/init", method="post")
          input#inputEventName(type="text", name="name", placeholder="name")
          input#inputHashtag(type="text", name="track", placeholder="track")
          button#buttonSubmit(type="submit") submit
$('formInit').on('submit', function(e) {
 e.preventDefault();

Remove the return false; You also don't have a class or ID specified in the selector. Changed the event binding to use the .on method.

Hope this helps.

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