Rails如何使用ajax提交表单,并包含一些jquery变量。

时间:2022-11-24 12:58:30

I'm trying to submit a form via ajax and include some variables that i'm setting via jquery.

我尝试通过ajax提交表单,并包含一些通过jquery设置的变量。

/views/applications/_form.html.erb

/ /应用程序/ _form.html.erb观点

<%= form_for(@application, :html => {:class => "organizer"}, :remote => true) do |f| %>
  // fields in here
<% end %>

/controllers/applications_controller.rb

/控制器/ applications_controller.rb

  # PUT /applications/1
  # PUT /applications/1.json
  def update
    @application = Application.find(params[:id])
    p params[:xposition]     # these get set in jquery
    p params[:application]   # these get set in jquery
    respond_to do |format|
      if @application.update_attributes(params[:application])
        @curr_app = ApplicationField.last

        format.html { redirect_to @application, notice: 'Application was successfully updated.' }
        format.json { head :no_content }
        format.js { render action: "update" }
      else
        format.html { render action: "edit" }
        format.json { render json: @application.errors, status: :unprocessable_entity }
        format.js { render action: "update" }
      end
    end
  end

/assets/javascripts/applications.js

/ / javascript / applications.js资产

$('.organizer').submit(function() {

        var dataToSubmit = $(this).serialize();
        var field_values = [];
        var x_values = [];
        var y_values = [];

        // i add values to the arrays above here

        for(i = 0; i < field_values.length; ++i) {
            dataToSubmit += "&field_name="+field_values[i]+"&xposition="+x_values[i]+"&yposition="+y_values[i];
        }

        $.post($(this).attr('action'), dataToSubmit);   
    });

With my current code, when the form is submitted, it goes directly to the controller, and then the $.post call in my jquery code calls the same controller and passes xpostion and yposition in the data of the $.post call (which is what i want).

在我的当前代码中,当表单提交时,它直接指向控制器,然后是$。在我的jquery代码中调用同一个控制器,并在$的数据中传递xpostion和yposition。打个电话(这是我想要的)。

How can i make it so only my form doesn't get submitted twice - once by hitting the controller as soon as the submit button is clicked and once from my $.post call?

我如何才能使它如此,只有我的表单没有提交两次-一次通过点击控制器,提交按钮被点击,一次从我的$。post调用吗?

I thought :remote => true makes it so the form wouldn't call the controller directly?

我想:remote => true,所以表单不会直接调用控制器?

EDIT

编辑

If :remote => true sends an ajax request without me having to use jquery's $.post method to send the ajax request manually, how can i send extra variables along with the ajax request that automatically gets made by using :remote => true?

如果:remote => true发送一个ajax请求,而不需要我使用jquery的$。post方法手动发送ajax请求,如何通过使用:remote => true的ajax请求发送额外的变量?

EDIT

编辑

Here's a snippet from my server log

这是我的服务器日志中的一个片段。

Started PUT "/applications/3" for 127.0.0.1 at 2013-01-18 00:06:19 -0600
Processing by ApplicationsController#update as */*
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"3LOzuiL/PU6HypJ4OeN5H9yrX3Xyk0VT6XpcFYd1wY0=", "application"=>{"application_field_attributes"=>{"0"=>{"id"=>"8"}, "1"=>{"id"=>"9"}}}, "field_name"=>"aaa", "xposition"=>"0", "yposition"=>"0", "id"=>"3"}
  Account Load (0.3ms)  SELECT `accounts`.* FROM `accounts` WHERE `accounts`.`subdomain` = 'localhost' LIMIT 1
  User Load (0.4ms)  SELECT `users`.* FROM `users` WHERE `users`.`id` = 1 LIMIT 1
  Application Load (0.4ms)  SELECT `applications`.* FROM `applications` WHERE `applications`.`id` = 3 LIMIT 1


Started PUT "/applications/3" for 127.0.0.1 at 2013-01-18 00:06:19 -0600
Processing by ApplicationsController#update as JS
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"3LOzuiL/PU6HypJ4OeN5H9yrX3Xyk0VT6XpcFYd1wY0=", "application"=>{"application_field_attributes"=>{"0"=>{"id"=>"8"}, "1"=>{"id"=>"9"}}}, "commit"=>"Submit", "id"=>"3"}
  Account Load (0.3ms)  SELECT `accounts`.* FROM `accounts` WHERE `accounts`.`subdomain` = 'localhost' LIMIT 1
  User Load (0.3ms)  SELECT `users`.* FROM `users` WHERE `users`.`id` = 1 LIMIT 1
  Application Load (0.4ms)  SELECT `applications`.* FROM `applications` WHERE `applications`.`id` = 3 LIMIT 1

2 个解决方案

#1


1  

You can try to stop all handlers except yours. Try this:

您可以尝试停止所有的处理程序,除了您的。试试这个:

$('.organizer').submit(function(e) {
  e.preventDefault(); // stops default behavior
  e.stopPropagation(); // prevents event bubbling
  // you code
  return false;
});

#2


1  

You can prevent the for from being submitted normally by preventing its default behaviour. To do this add an event parameter to you function and call .preventDefault()

您可以通过阻止它的默认行为来阻止其正常提交。为此,向您的函数添加一个事件参数并调用。preventdefault ()

$('.organizer').submit(function(e) {
        e.preventDefault();
        var dataToSubmit = $(this).serialize();
        var field_values = [];
        var x_values = [];
        var y_values = [];

        // i add values to the arrays above here

        for(i = 0; i < field_values.length; ++i) {
            dataToSubmit += "&field_name="+field_values[i]+"&xposition="+x_values[i]+"&yposition="+y_values[i];
        }

        $.post($(this).attr('action'), dataToSubmit);   
    });

#1


1  

You can try to stop all handlers except yours. Try this:

您可以尝试停止所有的处理程序,除了您的。试试这个:

$('.organizer').submit(function(e) {
  e.preventDefault(); // stops default behavior
  e.stopPropagation(); // prevents event bubbling
  // you code
  return false;
});

#2


1  

You can prevent the for from being submitted normally by preventing its default behaviour. To do this add an event parameter to you function and call .preventDefault()

您可以通过阻止它的默认行为来阻止其正常提交。为此,向您的函数添加一个事件参数并调用。preventdefault ()

$('.organizer').submit(function(e) {
        e.preventDefault();
        var dataToSubmit = $(this).serialize();
        var field_values = [];
        var x_values = [];
        var y_values = [];

        // i add values to the arrays above here

        for(i = 0; i < field_values.length; ++i) {
            dataToSubmit += "&field_name="+field_values[i]+"&xposition="+x_values[i]+"&yposition="+y_values[i];
        }

        $.post($(this).attr('action'), dataToSubmit);   
    });