jQuery 以ajax方式在rails 3中提交表单(使用jQuery)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6723334/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 21:17:47  来源:igfitidea点击:

Submit form in rails 3 in an ajax way (with jQuery)

jqueryajaxruby-on-rails-3

提问by katie

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.

我是 Rails 和 jQuery 的初学者。我在一个页面中有两个单独的表单,我想以 ajax 方式(使用 jQuery)分别提交它们。这是我走了多远。任何人都可以添加或修复此代码以使其工作。我正在使用 Rails 3.1 和 jQuery 1.6。先感谢您。

application.js

应用程序.js

$(".savebutton").click(function() { 
    $('form').submit(function() {
         $(this).serialize();
    });
}); 

first form:

第一种形式:

<%=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%>

second form:

第二种形式:

<%=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%>

SchoolController

学校管理员

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 is in the same shape as SchoolController

CourseController 与 SchoolController 的形状相同

回答by Johan

You want to:

你想要:

  1. Stop the normal behaviour of submit.
  2. Send it through ajax to the server.
  3. Get a reply back and change things accordingly.
  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
});

回答by Mild Fuzz

If you use :remote => trueon your forms, you can submit them with JavaScript with

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

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

回答by lulalala

The preferred way in Rails 3 to do ajax form submission is to utilize Rails-ujs.

在 Rails 3 中进行 ajax 表单提交的首选方法是利用 Rails-ujs。

Basically you allow Rails-ujs to do the ajax submit for you (and you won't need to write any js code). Then you just write js code to capture the response event (or other events) and do your thing.

基本上你允许 Rails-ujs 为你做 ajax 提交(你不需要编写任何 js 代码)。然后你只需编写 js 代码来捕获响应事件(或其他事件)并做你的事情。

Here are some code:

下面是一些代码:

First, use the remoteoption in form_forso form will submit via ajax by default:

首先,在form_for 中使用remote选项,以便表单默认通过 ajax 提交:

form_for :users, remote:true do |f|

Then when you want to do some action based on ajax response status (e.g. successful response), write the javscript logic like this:

然后当你想根据ajax响应状态做一些动作(例如响应成功)时,写这样的javscript逻辑:

$('#your_form').on('ajax:success', function(event, data, status, xhr) {
  // Do your thing, data will be the response
});

There are several eventswhich you can hook to.

几个事件可以挂钩。

回答by bassneck

To submit form via AJAX you could just pass :remote => trueto the form_forhelper. By default rails 3.0.x uses prototype js lib, but you can change it to jquery with the jquery-railsgem (which is the default for rails 3.1). bundle installit and then rails g jquery:installto replace the prototype files with jquery.

要通过 AJAX 提交表单,您只需传递:remote => trueform_for助手即可。默认情况下,rails 3.0.x 使用原型 js lib,但您可以使用jquery-railsgem将其更改为 jquery (这是 rails 3.1 的默认设置)。bundle install然后rails g jquery:install用jquery替换原型文件。

After that you'll just need to handle the callback. Take a look at thisscreencast

之后,您只需要处理回调。看看这个截屏视频

回答by Ezequiel García

it's very important in your request with ajax stop the beahavior default, send remote:true in your form_for

在您的请求中使用 ajax 停止默认行为非常重要,在您的 form_for 中发送 remote:true

<%= form_for :session, url: sessions_path, remote: true, html: { class: "form-signin" } do |f| %>

<% end %>

in your ajax

在你的阿贾克斯

$(".form-signin").on("submit", function(e) {
    $.ajax({
        url: $(this).attr('action'),
        data: $(this).serialize(),
        type: "POST",
        dataType: "json",
        success: function(response) {
            console.log(response)
        },
        error: function(xhr, textStatus, errorThrown) {}
    });
    e.preventDefault(); //THIS IS VERY IMPORTANT
});

回答by Mike Bethany

Nothing here worked for me, my issue was the jQuery modal library would break my forms from being submitted via remote data if I brought up a modal window, but I found a fix.

这里没有什么对我有用,我的问题是如果我打开一个模态窗口,jQuery 模态库会破坏我的表单通过远程数据提交,但我找到了一个修复。

First add the jQuery Form Plugin to your assets javascript directory: http://malsup.github.io/jquery.form.js

首先将 jQuery 表单插件添加到您的资产 javascript 目录:http: //malsup.github.io/jquery.form.js

Now override the submit method for your form. For example you could do something like this:

现在覆盖表单的提交方法。例如,您可以执行以下操作:

= form_for @object, html: {class: "ajax_form_submit"}, authorization_token: true do |f|
  = f.text_input

javascript:

  $(document).on('ready page:load', function() {

    $(".ajax_form_submit").submit(function () {
      var form = $(this)
      form.ajaxSubmit({
        success: function (responseText, statusText, xhr) {
          console.log('success: ajax_form_submit')
        },
        error: function (jqXHR, statusText, errorThrown) {
          console.log('error: ajax_form_submit');
          console.log(jqXHR, statusText, errorThrown);
        }
      })
    })

  })