在轨道3在Ajax方式提交表单(使用jQuery) [英] Submit form in rails 3 in an ajax way (with jQuery)
本文介绍了在轨道3在Ajax方式提交表单(使用jQuery)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在铁轨和jQuery的初学者。我有两个不同的形式在一个页面上,我想在阿贾克斯的方式(使用jQuery)分别提交。这是我有多远了。任何人都可以增加或修正此code,使其工作。我用Rails 3.1和jQuery 1.6。先感谢您。
I am a beginner in rails and jQuery. I have two separate forms in one page and I want to submit them separately in ajax way (with jQuery). This is how far I got. Can anybody add or fix this code to make it work. I am using Rails 3.1 and jQuery 1.6. Thank you in advance.
的application.js
application.js
$(".savebutton").click(function() {
$('form').submit(function() {
$(this).serialize();
});
});
第一种形式:
first form:
<%=form_for :users do |f| %>
<fieldset>
<legend>Basic details</legend>
<%= f.label :school %>
<%= f.text_field :school,:size=>"45",:class=>"round",:id=>"school" %><br/>
</fieldset>
<p><%= button_to "save and continue",{:class=>"savebutton"} %></p>
<%end%>
第二种形式:
second form:
<%=form_for :courses do |c| %>
<fieldset>
<legend>Your current classes</legend>
<label>class:</label><%= c.text_field :subject,:size=>"45",:class=>"round" %><br/>
</fieldset>
<p><%= button_to "save and continue",{:class=>"savebutton"} %></p>
<%end%>
SchoolController
SchoolController
class SchoolController < ApplicationController
respond_to :json
def create
@school = current_user.posts.build(params[:school].merge(:user => current_user))
if @school.save
respond_with @school
else
respond_with @school.errors, :status => :unprocessable_entity
end
end
end
CourseController是在相同的形状SchoolController
CourseController is in the same shape as SchoolController
推荐答案
您想:
- 停止提交的正常行为。
- 通过AJAX给服务器发送。
- 在得到答复背部和相应改变的东西。
在code以下应该做的:
The code below should do that:
$('form').submit(function() {
var valuesToSubmit = $(this).serialize();
$.ajax({
type: "POST",
url: $(this).attr('action'), //sumbits it to the given url of the form
data: valuesToSubmit,
dataType: "JSON" // you want a difference between normal and ajax-calls, and json is standard
}).success(function(json){
console.log("success", json);
});
return false; // prevents normal behaviour
});
这篇关于在轨道3在Ajax方式提交表单(使用jQuery)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文