我有一个简单的控制器,我已经响应html和json.我正在使用json响应用于Backbone应用程序.一切都按预期工作,除了当我单击使用show方法的链接,然后单击后退按钮时,索引方法只是将一大串
JSON打印到浏览器中.如果我刷新,它会按预期显示HTML.这是控制器.
- 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?添加一个检查,如果它是一个AJAX请求,只渲染JSON,但这不起作用.
编辑
这是一个不使用turbolinks的Rails 3应用程序.
编辑2
这是相关的Backbone代码.
- # 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
和/recipes.json
和/recipes/1.html和/recipes/1.json
而不是依靠骨干和历史总是发送正确的标头