我是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,:size=>"45",: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
发布于 2018-03-02 10:33:37
你想:
下面的代码应这样做:
$('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
});
发布于 2018-03-02 10:55:48
在你的表单上如果你用:remote => true
,可以使用JavaScript将它们提交给
$('form#myForm').trigger('submit.rails');
https://stackoverflow.com/questions/-100003556
复制相似问题