2011-11-30 56 views
4

在rails中,需要進行哪種AJAX調用才能創建和修改資源。說,如果我有一個資源這樣使用AJAX的Rails資源

Man(age: integer, country_from:string, residence:string) 

現在怎麼會變成這樣,通過一個AJAX調用進行(如發送後到我的創造功能,如何將參數發送中,如何將我的控制器進行設置)。詳細一點,我的AJAX非常,非常非常弱。 (現在,我有我的人爲像鐵軌產生支架男年齡:INT country_from:串...)使用

PS

林軌3

回答

1

所以我相信這有兩個方面:JavaScript和控制器改變。

在你的控制器,你需要確保它可以返回JSON輸出(或XML或任何你選擇的AJAX-Y輸出):

def man 
    # do your work 
    return_data = {} 
    # initialize your return data 
    respond_to do |format| 
    render :json => return_data.to_json, :layout => nil 
    end 
end 

有很多種方法來生成JSON輸出,但基本上你有以確保它的形狀很容易在javascript視圖中使用。

我使用jQuery和這裏的執行Ajax調用的代碼:

function foo(some_param) { 
    $.ajax({ 
    type: 'GET', 
    url: "/<controller>/man?FOO=" + some_params, 
    dataType: 'json', 
    success: handle_success, 
    error: handle_errors 
} 

function handle_success(data) { 
    # process return JSON. it's a javascript object corresponding to the shape 
    # of your JSON. If your json was a hash server side, it will be an 'object', etc 
} 

function handle_error(data) { 
    # handle error cases based upon failure in the infrastructure, not 
    # failure cases that you encounter due to input, etc. 
} 

可以配合foo的功能,一些按鈕或作爲的onclick你的願望。

我不確定這是否完整。讓我知道如果你需要更多的細節,等等

1

的Rails 3可以告訴你希望它是「遠程」的形式幫助(阿賈克斯)

<%= form_for @man, :remote=>true do |f| %> 
    <div class="field"> 
    <%= f.label :man %> 
    <%= f.text_field :man %> 
    </div> 
    <%= f.submit "Save", :disable_with=>"Saving..."%> 
<% end %> 
在你的控制器

class MansController < ApplicationController 
    respond_to :js, :html 

    def update 
    @man = Man.find(params[:id]) 
    @man.update_attributes(params[:man]) 
    respond_with @man 
    end 
end 

然後,你可以有 /app/views/mans/update.js.erb

<% if @man.errors.any? %> 
    alert("This is javascript code that either renders the form in place of the other form"); 
<% else %> 
    alert("success!") 
<% end %> 

注:無論我說「男人「上面,它可能是」男人「