以Ajax方式在Rails 3中提交表单(使用jQuery)

我是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

CourseController与SchoolController的形状相同


UYOU
浏览 448回答 3
3回答

紫衣仙女

你想要:停止提交的正常行为。通过ajax将其发送到服务器。收到回复并相应地进行更改。下面的代码应该这样做:$('form').submit(function() {&nbsp;&nbsp;&nbsp; &nbsp; var valuesToSubmit = $(this).serialize();&nbsp; &nbsp; $.ajax({&nbsp; &nbsp; &nbsp; &nbsp; type: "POST",&nbsp; &nbsp; &nbsp; &nbsp; url: $(this).attr('action'), //sumbits it to the given url of the form&nbsp; &nbsp; &nbsp; &nbsp; data: valuesToSubmit,&nbsp; &nbsp; &nbsp; &nbsp; dataType: "JSON" // you want a difference between normal and ajax-calls, and json is standard&nbsp; &nbsp; }).success(function(json){&nbsp; &nbsp; &nbsp; &nbsp; console.log("success", json);&nbsp; &nbsp; });&nbsp; &nbsp; return false; // prevents normal behaviour});

喵喵时光机

如果您:remote => true在表单上使用,则可以使用JavaScript通过以下方式提交它们:$('form#myForm').trigger('submit.rails');

FFIVE

在Rails 3中进行Ajax表单提交的首选方法是利用Rails-ujs。基本上,您允许Rails-ujs为您完成ajax提交(并且您无需编写任何js代码)。然后,您只需编写js代码以捕获响应事件(或其他事件)并执行您的操作即可。这是一些代码:首先,在form_for中使用remote选项,因此默认情况下,表单将通过ajax提交:form_for :users, remote:true do |f|然后,当您要基于ajax响应状态(例如,成功响应)执行某些操作时,请编写如下的javscript逻辑:$('#your_form').on('ajax:success', function(event, data, status, xhr) {&nbsp; // Do your thing, data will be the response});有几个事件,你可以钩住。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JQuery