如何使用jQuery UJS在選擇框的更改事件在Rails中觸發後提交表單?如何使用jQuery UJS在Rails中選擇框的更改事件觸發後通過AJAX提交表單?
我的看法是這樣的:
<% 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 %>
非常簡單。我的控制器就像這樣:
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
而且在我的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?
});
})
請注意,表單提交火就好了。但它正在做一個常規帖子,而不是一個AJAX提交。當我在表單上放置一個提交按鈕並使用它時,AJAX提交工作正常。我需要更改:
this.form.submit();
給一個AJAX調用,但我不知道如何。誰能幫忙?
感謝雨果。我實際上今天觀看了這個截屏視頻,並嘗試了這個例子。爲了引用表單,我使用了「this.form.submitWithAjax();」因爲我試圖從選擇框的更改事件中引用表單。我一直在收到「submitWithAjax不是函數」。 – AKWF 2010-11-16 21:13:41
我無法嘗試此操作,但可以在submitWithAjax定義中將this.submit(....)這一行更改爲this.form.submit(....)。也許你試過idk。讓我知道。 – Hugo 2010-11-16 21:17:15
是的,這對我來說沒有任何結合。這非常非常令人沮喪。我終於沒有得到這個工作: $( 「#permission_action」)改變(函數(){ \t \t $阿賈克斯({ 類型: 「PUT」, 網址:this.form.action, 數據: 「許可[動作] =」 + $( 「#permission_action」)VAL() }); 返回假; }); 但它只適用於第一線!屏幕上的每一行都帶有一個名爲「permission_action」的選擇框。我沒有意識到jQuery只會默認綁定到特定名稱的第一個元素。 – AKWF 2010-11-16 21:25:04