2012-07-13 28 views
0

在我的Ruby on Rails代碼中,我想將json響應發送回客戶端。由於我是紅寶石新手,我不知道我該怎麼做。我想送error = 1 and success = 0爲JSON數據,如果數據不保存到數據庫中,如果它成功地保存它應該發送success = 1 and error = 0請參考下面如何將json響應傳遞迴客戶端

這裏是我的控制器

class ContactsController < ApplicationController 
    respond_to :json, :html 
    def contacts 
    error = 0 
    success = 1 

    @contacts = Contact.new(params[:contact]) 

    if @contacts.save 
     respond_to do |format| 
     format.json { render :json => @result.to_json } 
     end 
    else 
     render "new" 
    end 
    end 
end 

我的代碼這裏是我的javascript代碼

$('.signupbutton').click(function(e) { 
     e.preventDefault(); 
     var data = $('#updatesBig').serialize(); 
     var url = 'contacts'; 
     console.log(data); 
     $.ajax({ 
      type: 'POST', 
      url: url, 
      data: data, 
      dataType: 'json', 
      success: function(data) { 
       console.log(data); 
      } 
     }); 
    }); 
+0

查找到 「的respond_to做|格式|」因爲這是你通常對不同的請求格式,html,xml,json等的響應。 – railsdog 2012-07-13 11:42:51

+0

@railsdog我將這段代碼添加到我的代碼中if @ contacts.save respond_to do | format | format.json {render:json => @ result.to_json} end else render「new」 end'但這不起作用。它甚至沒有顯示任何錯誤。 – 2619 2012-07-13 11:43:56

+0

我想你會很難得到這個AJAX請求來觸發'contacts'控制器中的'contacts'動作。 我認爲這是值得看看Rails指南路由 - http://guides.rubyonrails.org/routing.html – mylescarrick 2012-07-13 11:46:37

回答

4

有噸的其他優雅的方式,但這是正確的:

class ContactsController < ApplicationController 

    def contacts 
    @contacts = Contact.new(params[:contact]) 
    if @contacts.save 
     render :json => { :error => 0, :success => 1 } 
    else 
     render :json => { :error => 1, :success => 0 } 
    end 
    end 

end 

另外添加一個route.rb的路由。如果您需要使用html響應,則必須包含respond_to do | format |。

0

你要調整你的路線,接受JSON數據

match   'yoururl' => "contacts#contacts", :format => :json 

然後它會工作

相關問題