使用Sinatra和jQuery而无需在POST上进行重定向 [英] Using Sinatra and jQuery without redirecting on POST
问题描述
我正在尝试使用jQuery向我的Sinatra应用程序提交表单,但是当通过AJAX发布时,Sinatra应用程序显示空白页.我希望它停留在同一页面上,并更新我在javascript中指定的内容.这是我的代码,简写如下:
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
这是haml文件中的我的javascript:
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")
}
});
});
});
推荐答案
尝试一下,
$(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(...
检测表单提交. e.preventDefault();
阻止表单提交.其余的提交Ajax请求.
$("form#the_id").submit(...
detects the form submission. e.preventDefault();
prevents the form submission. The rest submits an Ajax request.
别忘了将#the_id
更改为您的表单ID.
Don't forget to change #the_id
to your form id.
这篇关于使用Sinatra和jQuery而无需在POST上进行重定向的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!