ruby-on-rails – Rails控制器在浏览器中呈现JSON

前端之家收集整理的这篇文章主要介绍了ruby-on-rails – Rails控制器在浏览器中呈现JSON前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个简单的控制器,我已经响应html和json.我正在使用json响应用于Backbone应用程序.一切都按预期工作,除了当我单击使用show方法链接,然后单击后退按钮时,索引方法只是将一大串 JSON打印到浏览器中.如果我刷新,它会按预期显示HTML.这是控制器.
  1. class RecipesController < ApplicationController
  2. def index
  3. @user = User.find(params[:user_id])
  4. @recipes = Recipe.all
  5.  
  6. respond_to do |format|
  7. format.html
  8. format.json { render json: Recipe.where(user_id: params[:user_id]).featured }
  9. end
  10. end
  11. ...
  12. end

我尝试为response.xhr?添加一个检查,如果它是一个AJAX请求,只渲染JSON,但这不起作用.

编辑

这是一个不使用turbolinks的Rails 3应用程序.

编辑2

这是相关的Backbone代码.

  1. # app/assets/javascripts/collections/recipe_list_.js.cofee
  2. @App.Collections.RecipeList = Backbone.Collection.extend
  3. url: ->
  4. "/users/#{@userId}/recipes"
  5. model: window.App.Models.Recipe
  6. initialize: (opts) ->
  7. @userId = opts.userId
  8.  
  9.  
  10. # app/assets/javascripts/app.js.coffee
  11. $->
  12. urlAry = window.location.href.split('/')
  13. userId = urlAry[urlAry.length - 2]
  14. App = window.App
  15. App.recipeList = new App.Collections.RecipeList(userId: userId)
  16. App.recipeListView = new App.Views.RecipeListView

解决方法

你可以尝试使用/recipes.html
和/recipes.json
和/recipes/1.html和/recipes/1.json

而不是依靠骨干和历史总是发送正确的标头

猜你在找的Ruby相关文章