【发布时间】:2011-03-16 09:59:25
【问题描述】:
我有一个简单的搜索表单,看起来像:
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);
});
})
我遇到的问题是,当我在 JSON 中呈现错误的 400 时,如何在 ajax:error 处理程序中获取该 JSON?使用萤火虫我可以看到数据/消息似乎存储在 xhr.responseText 作为字符串,而不是 JSON。 'ajax:success' 处理程序似乎在 'data' 参数中获取了实际的 JSON 数据。
我正在使用 Rails 3 + jQuery (UJS)。
【问题讨论】: