ruby-on-rails - Rails Controller 在浏览器中呈现 JSON

标签 ruby-on-rails json

我有一个简单的 Controller ,我可以同时响应 htmljson .我正在使用 json Backbone 应用程序的响应。一切都按预期工作,除了当我单击使用 show 的链接时方法,然后单击返回按钮,index方法只是打印一个大字符串 JSON进入浏览器。如果我刷新,它会按预期显示 HTML。这是 Controller 。

class RecipesController < ApplicationController
  def index
    @user = User.find(params[:user_id])
    @recipes = Recipe.all

    respond_to do |format|
      format.html
      format.json { render json: Recipe.where(user_id: params[:user_id]).featured }
    end
  end
  ...
end
我尝试为 response.xhr? 添加支票,并且只渲染 JSON如果它是一个 AJAX 请求,但那没有用。
编辑
这是一个不使用 turbolinks 的 Rails 3 应用程序。
编辑 2
这是相关的主干代码。
# app/assets/javascripts/collections/recipe_list_.js.cofee
@App.Collections.RecipeList = Backbone.Collection.extend
  url: ->
    "/users/#{@userId}/recipes"
  model: window.App.Models.Recipe
  initialize: (opts) ->
    @userId = opts.userId


# app/assets/javascripts/app.js.coffee
$ ->
  urlAry = window.location.href.split('/')
  userId = urlAry[urlAry.length - 2]
  App = window.App
  App.recipeList = new App.Collections.RecipeList(userId: userId)
  App.recipeListView = new App.Views.RecipeListView

最佳答案

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

而不是依靠主干和历史来始终发送正确的 header

关于ruby-on-rails - Rails Controller 在浏览器中呈现 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26531024/

相关文章:

ruby-on-rails - 是否在观察者中访问 session 是个好主意?

html - WrapBootstrap 模板不起作用

ruby-on-rails - 新摄影与铁路

javascript - ajax 调用后获取旧数据(get 方法)Laravel 5.5

php - JSON编码mysql查询

arrays - Symfony3 从查询返回数组到 json

ruby-on-rails - 将 will_paginate 与多个模型一起使用(Rails)

ruby-on-rails - 如何更改此 ruby​​ 匹配线以返回 true 或 false

json - 如何在 JSON 文件中添加 terraform 变量

python - [删除]从 JSON 字典中删除一个项目会留下一个空字典 : `{}` . 如何完全删除它?