在Rails中选择框的更改事件触发后,如何使用jQuery UJS通过AJAX提交表单?

AKW*_*KWF 5 ajax jquery ruby-on-rails

在Rails中选择框的更改事件触发后,如何使用jQuery UJS提交表单?

我的观点如下:

<% for perm in @permissions %>
  <%= form_for [@brand,perm], { :remote => true } do |f| %>
    <tr id="permission_<%= perm.id %>">
      <td><%= perm.configurable.name %></td>
      <td><%= f.select :action, ['none', 'read', 'update', 'manage'] %></td>
    </tr>
  <% end %>
<% end %>
Run Code Online (Sandbox Code Playgroud)

非常直截了当.我的控制器是这样的:

class PermissionsController < ApplicationController

    before_filter :authenticate_user!

    respond_to :html, :js

    load_and_authorize_resource :brand
    load_and_authorize_resource :permission, :through => :brand

    def index
    end

    def update
      @permission = Permission.find(params[:id])
      @permission.update_attributes(params[:permission])
    end

end
Run Code Online (Sandbox Code Playgroud)

在我的application.js中:

// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults
$(function() {
  $("#permission_action").change(function() {
    this.form.submit(); // This needs to be an AJAX call, but how?
  });
})
Run Code Online (Sandbox Code Playgroud)

请注意,表单提交正常.但它正在做一个常规的帖子,而不是一个AJAX提交.当我在表单上放置一个提交按钮并使用它时,AJAX提交工作正常.我需要改变:

this.form.submit();
Run Code Online (Sandbox Code Playgroud)

一个AJAX电话,但我不知道如何.有人可以帮忙吗?

Hug*_*ugo 3

我发现您已经在使用 jQuery,这很好。以下代码取自此处:http ://railscasts.com/episodes/136-jquery

我强烈建议您熟悉这些屏幕截图,它们有很大帮助(轻描淡写)。

// public/javascripts/application.js
jQuery.ajaxSetup({ 
  'beforeSend': function(xhr) {xhr.setRequestHeader("Accept", "text/javascript")}
})

jQuery.fn.submitWithAjax = function() {
  this.submit(function() {
    $.post(this.action, $(this).serialize(), null, "script");
    return false;
  })
  return this;
};

$(document).ready(function() {
  $("#new_review").submitWithAjax();
})
Run Code Online (Sandbox Code Playgroud)