我是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 学校控制器 < 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 is in the same shape as 学校控制器

推荐答案

您想要:

  1. Stop the normal behaviour of submit.
  2. 通过ajax将其发送到服务器.
  3. 得到回复,并做出相应的更改.

下面的代码应该可以做到这一点:

$('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
});

Jquery相关问答推荐

如何使用 jQuery 强制悬停状态?

使用 jQuery $.ajax() 时如何使用 GET 在请求正文中发送数据

如何在 jQuery 中使用:not 和 hasClass() 来获取没有类的特定元素

提高 jQuery Select 器性能的好方法?

在 JavaScript 中解析 URL

在jQuery中获取所有选定复选框值的最佳方法

使用 jQuery Validate 确认密码

如何使用Angular 检测浏览器后退按钮单击事件?

在javascript中检测按键的最简单方法

jquery变量语法

如何使用jQuery在弹出窗口中预览输入类型=文件中的选定图像?

如何使用 Javascript/jQuery 确定图像是否已加载?

未捕获的 TypeError:data.push 不是函数

按文本 Select 链接(完全匹配)

所有但不是jQuery Select 器

jQuery从字符串中删除'-'字符

检测 jQuery UI 对话框是否打开

使用中键触发 onclick 事件

detach()、hide() 和 remove() 之间的区别 - jQuery

如何让 jQuery 等到效果完成?