为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

UYOU 2019-12-10 09:28:47
我是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  endendCourseController与SchoolController的形状相同
查看完整描述

3 回答

?
紫衣仙女

TA贡献1839条经验 获得超15个赞

你想要:


停止提交的正常行为。

通过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

});


查看完整回答
反对 回复 2019-12-10
?
喵喵时光机

TA贡献1846条经验 获得超7个赞

如果您:remote => true在表单上使用,则可以使用JavaScript通过以下方式提交它们:


$('form#myForm').trigger('submit.rails');


查看完整回答
反对 回复 2019-12-10
?
FFIVE

TA贡献1797条经验 获得超6个赞

在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) {

  // Do your thing, data will be the response

});

有几个事件,你可以钩住。


查看完整回答
反对 回复 2019-12-10
  • 3 回答
  • 0 关注
  • 444 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信