我有一个简单的搜索表单,如下所示:
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?使用 firebug 我可以看到数据/消息似乎作为字符串而不是 JSON 存储在 xhr.responseText 中。 “ajax:success”处理程序似乎在“data”参数中获取实际的 JSON 数据。
我正在使用 Rails 3 + jQuery (UJS)。
最佳答案
您可以使用jQuery.parseJSON
将xhr.responseText
转换为JSON对象:
http://api.jquery.com/jQuery.parseJSON/
console.log("error json: ", jQuery.parseJSON(xhr.responseText));
关于jquery - Rails 3 Unobtrusive JavaScript - 处理 JSON 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5323620/