Rails 3 Unobtrusive JavaScript - 处理JSON响应

cod*_*aig 4 jquery ruby-on-rails-3

我有一个简单的搜索表单,看起来像:

应用程序/视图/搜索/ index.html.erb

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

*应用程序/控制器/ 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
Run Code Online (Sandbox Code Playgroud)

公共/ 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);
        });
})
Run Code Online (Sandbox Code Playgroud)

我遇到的问题是,当我使用JSON中的错误渲染400时,如何在ajax:错误处理程序中获取该JSON?使用firebug我可以看到数据/消息似乎作为String存储在xhr.responseText中,而不是JSON.'ajax:success'处理程序似乎在'data'参数中获取实际的JSON数据.

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

Ada*_*res 6

您可以使用jQuery.parseJSON将其xhr.responseText转换为JSON对象:

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

console.log("error json: ",  jQuery.parseJSON(xhr.responseText));
Run Code Online (Sandbox Code Playgroud)