2011-03-16 3 views
4

:레일 3 겸손한 자바 스크립트 - 처리 JSON 응답 내가 좋아하는 뭔가를 보이는 간단한 검색 양식이

응용 프로그램/조회/검색/index.html.erb

<%= form_for @search, :as => :search, :remote => true, :url => {:action => "query"}, :html => {:id => 'search-form'} do |f| %> 
    ... 
<% end % 

* 응용 프로그램/컨트롤러 /search_controller.rb*

def index 
    @search = SearchCriteria.new 
end 

def query 
    @search = SearchCriteria.new(params[:search]) 

    unless @search.valid? 
    respond_to do |format| 
     format.json { render :json => {:error => 'validation failed'}, :status => 400 } 
    end 
    return 
    end 

    # otherwise, perform search... 

    render :json => @results 
end 

공공/자바 스크립트는/

012 application.js
$(function() { 
    $('search-form') 
     .bind('ajax:success', function(e, data, status, xhr) { 
      console.log("data=" + data); 
     }) 
     .bind('ajax:error', function(e, xhr, status, error) { 
      console.log("error json: " + xhr.responseText); 
     }); 
}) 

문제는 제가 JSON에서 400 오류를 렌더링 할 때 어떻게 그 JSON을 ajax : error 핸들러에서 얻을 수 있습니까? 방화 광구를 사용하여 데이터/메시지가 xhr.responseText에 JSON이 아닌 String으로 저장되어있는 것으로 나타났습니다. 'ajax : success'핸들러는 'data'매개 변수에서 실제 JSON 데이터를 가져 오는 것으로 보입니다.

저는 Rails 3 + jQuery (UJS)를 사용하고 있습니다.

답변

6

당신은 JSON 객체로 xhr.responseText를 설정하는 jQuery.parseJSON를 사용할 수 있습니다

http://api.jquery.com/jQuery.parseJSON/

console.log("error json: ", jQuery.parseJSON(xhr.responseText)); 
+0

우수 ... 난 그냥 여기로 오기 전에 답변을 볼 것으로 나타났다. 한 가지 다른 측면의 질문. 나는 오류 및/또는 플래시 메시지를 표시하기위한 기본/표준 레일보기와 비슷합니다. 내가 어디에서 그 코드를 찾을 수 있는지, HTML/CSS를 사용하여 오류를 표시하고 싶습니다. – codecraig

+0

죄송합니다. 레일에 익숙하지 않습니다. –

관련 문제