以ajax方式在rails 3中提交表单(使用jQuery) [英] Submit form in rails 3 in an ajax way (with jQuery)

查看:26
本文介绍了以ajax方式在rails 3中提交表单(使用jQuery)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Rails 和 jQuery 的初学者.我在一个页面中有两个单独的表单,我想以 ajax 方式(使用 jQuery)分别提交它们.这是我走了多远.任何人都可以添加或修复此代码以使其工作.我正在使用 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.

应用程序.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

CourseController 与 SchoolController 的形状相同

CourseController is in the same shape as SchoolController

推荐答案

您想要:

  1. 停止提交的正常行为.
  2. 通过ajax发送到服务器.
  3. 得到回复并相应地更改内容.

下面的代码应该这样做:

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
});

这篇关于以ajax方式在rails 3中提交表单(使用jQuery)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆