Using Sinatra and jQuery without redirecting on POST

a 夏天 提交于 2019-12-06 13:55:59

问题


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:


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.



来源:https://stackoverflow.com/questions/15377367/using-sinatra-and-jquery-without-redirecting-on-post

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!