2011-03-16 44 views
4

我有,看起來像一個簡單的搜索頁面:Rails 3的非侵入式JavaScript - 處理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 

公共/ Java腳本/ 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錯誤時,如何在ajax中獲取該JSON:錯誤處理程序?使用firebug我可以看到數據/消息似乎以xhr.responseText作爲字符串存儲,而不是JSON。 'ajax:success'處理程序似乎獲取'data'參數中的實際JSON數據。

我正在使用Rails 3 + jQuery(UJS)。

回答

6

您可以使用jQuery.parseJSON打開xhr.responseText成JSON對象:

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

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

優秀的...我只是發現,回來這裏之前看到你的答案。另一方面的問題。我有點像默認/標準的鋼軌視圖顯示錯誤和/或Flash消息。你知道我在哪裏可以找到該代碼,我想用他們的HTML/CSS顯示我的錯誤。 – codecraig 2011-03-16 10:12:31

+0

對不起,我不熟悉rails。 – 2011-03-16 10:40:58