2010-11-16 124 views
5

如何使用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調用,但我不知道如何。誰能幫忙?

回答

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(); 
}) 
+0

感謝雨果。我實際上今天觀看了這個截屏視頻,並嘗試了這個例子。爲了引用表單,我使用了「this.form.submitWithAjax();」因爲我試圖從選擇框的更改事件中引用表單。我一直在收到「submitWithAjax不是函數」。 – AKWF 2010-11-16 21:13:41

+1

我無法嘗試此操作,但可以在submitWithAjax定義中將this.submit(....)這一行更改爲this.form.submit(....)。也許你試過idk。讓我知道。 – Hugo 2010-11-16 21:17:15

+0

是的,這對我來說沒有任何結合。這非常非常令人沮喪。我終於沒有得到這個工作: $( 「#permission_action」)改變(函數(){ \t \t $阿賈克斯({ 類型: 「PUT」, 網址:this.form.action, 數據: 「許可[動作] =」 + $( 「#permission_action」)VAL() }); 返回假; }); 但它只適用於第一線!屏幕上的每一行都帶有一個名爲「permission_action」的選擇框。我沒有意識到jQuery只會默認綁定到特定名稱的第一個元素。 – AKWF 2010-11-16 21:25:04

4

通過jQuery的UJS來源來看,我想,這可能是最安全的方法:

// in application.js 
jQuery.fn.ajaxSubmit = function() { 
    this.trigger('submit.rails'); 
}; 

它只是作爲觸發將.submit(事件),但在UJS的味道,所以你會打電話

$('.my_form').ajaxSubmit(); 
相關問題