2012-07-13 4 views
0

레일즈 루비 코드에서 클라이언트에게 json 응답을 보내려고합니다. 레일에서 루비를 처음 접했을 때 나는 이것을 어떻게 할 수 있을지 모른다. 성공적으로 여기 내 자바 스크립트 코드가 success = 1 and error = 0json 응답을 클라이언트에 다시 전달하는 방법

여기

내 컨트롤러

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 

입니다 아래에 내 코드를 참조하십시오 보낼 것을 절약 할 수 있다면 데이터가 데이터베이스에 저장하지 않을 경우 JSON 데이터로 error = 1 and success = 0를 보낼과

$('.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

봐 작동합니다 JSON 데이터

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

를 허용하도록 경로를 조정해야 html, xml, json 등 다양한 요청 형식에 일반적으로 응답하는 방식입니다. – railsdog

+0

@railsdog이 코드를 제 코드에 추가했습니다. if @ contacts.save respond_to do | format | format.json {render : json => @ result.to_json} end else render "new" end' 그러나 이것은 작동하지 않습니다. 그것은 어떤 오류라도 보여주지 않습니다. – 2619

+0

AJAX 요청이'contacts' 컨트롤러의'contacts' 액션을 치려고 애 쓰고 있다고 생각합니다. 라우팅에 관한 레일 가이드를 살펴 보는 것이 가치 있다고 생각합니다. - http://guides.rubyonrails.org/routing.html – mylescarrick

답변

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 

routes.rb에 경로를 추가합니다. html 응답을 사용해야하는 경우 respond_to do | format |을 포함시켜야합니다. "| 형식 | 할 respond_to"

0

당신은에

관련 문제