我是rails和jQuery的初学者。我在一个页面中有两个单独的表单,我想以ajax方式(使用jQuery)单独提交它们。这是我有多远。任何人都可以添加或修复此代码,使其工作。我使用Rails 3.1和jQuery 1.6。先谢谢你。
application.js
$(".savebutton").click(function() {
$('form').submit(function() {
$(this).serialize();
});
});
第一种形式:
<%=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%>
第二种形式:
<%=form_for :courses do |c| %>
<fieldset>
<legend>Your current classes</legend>
<label>class:</label><%= c.text_field :subject,:class=>"round" %><br/>
</fieldset>
<p><%= button_to "save and continue",{:class=>"savebutton"} %></p>
<%end%>
学校控制器
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的形状相同
你想要:
>停止提交的正常行为。
>通过ajax发送到服务器。
>获得回复并相应地更改事情。
下面的代码应该这样做:
$('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
});