Using Sinatra and jQuery without redirecting on PO

2019-04-15 18:20发布

I am trying to use jQuery to submit a form to my Sinatra app, but when POSTing via the AJAX, the Sinatra app is displaying a blank page. I would like it to stay on the same page, and update the content I have specified in the javascript. Here is my code, stripped down:

post '/register' do
  register( params )
end
get '/register' do
  haml :register
end

And here is my javascript in the haml file:

:javascript
        $(function() {
                $("button#submit").click(function(){
                        $.ajax({
                                type: "POST",
                                url: "/register",
                                data: $('form.register').serialize(),
                                success: function(){
                                        $("#message").html("Successfully registered")
                                },
                                error: function(){
                                        $("#message").html("Not Successful")
                                }
                        });
                });
        });

1条回答
唯我独甜
2楼-- · 2019-04-15 18:57

Try this,

$(function() {
  $("form#the_id").submit(function(e){
    e.preventDefault();

    $.ajax({
      type: "POST",
      url: "/register",
      data: $('form.register').serialize(),
      success: function(){
        $("#message").html("Successfully registered")
      },
      error: function(){
        $("#message").html("Not Successful")
      }
    });
  });
});

$("form#the_id").submit(... detects the form submission. e.preventDefault(); prevents the form submission. The rest submits an Ajax request.

Don't forget to change #the_id to your form id.

查看更多
登录 后发表回答