Rails 3 Unobtrusive JavaScript - handle JSON response
I have a simple search form that looks something like:
app/views/search/index.html.erb
<%= form_for @search, :as => :search, :remote => true, :url => {:action => "query"}, :html => {:id => 'search-form'} do |f| %>
...
<% end %
*app/controllers/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
public/javascripts/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);
});
})
The problem I have is that wh开发者_开发技巧en I render a 400 with an error in JSON, how can I get that JSON in the ajax:error handler? Using firebug I could see that the data/message seems to be stored in xhr.responseText as a String, not as JSON. The 'ajax:success' handler seems to get the actual JSON data in the 'data' parameter.
I'm using Rails 3 + jQuery (UJS).
You can use jQuery.parseJSON
to turn the xhr.responseText
into a JSON object:
http://api.jquery.com/jQuery.parseJSON/
console.log("error json: ", jQuery.parseJSON(xhr.responseText));
精彩评论