0

当我尝试实现 ajax 时,出现“406 Not Acceptable in 13ms (ActiveRecord: 0.6ms)”错误。代码在没有任何respond_to块的普通 html 中工作。我已经将问题缩小到respond_to块,我现在很难过。SO & google 上相同错误的其他解决方案似乎均不适用或有效。

  1. respond_to使用仅包含 html 或 ajax/js的块时,是什么导致 406 错误?
  2. 如何修复 406 错误?
  3. 可以redirect_torespond_to块中使用format.html如下代码所示吗?

如果您需要更多信息,请告诉我。

查看(哈姆):

普通的html代码

%div.control-group.controls
  = button_to "Delete Gcal User", @gcal_user, method: :delete, class: "btn btn-danger"

AJAX 代码

%div.control-group.controls
  = button_to "Delete Gcal User", @gcal_user, method: :delete, remote: true, class: "btn btn-danger"

AJAX 的 JS 代码(咖啡脚本)

$('#calendar').empty();


控制器:

class GcalUsersController < ApplicationController
  def destroy
    @gcal_user = current_user.gcal_user
    # if @gcal_user.delete
    #   flash[:notice] = "#{@gcal_user.username} deleted"
    # end

    # redirect_to user_root_path  # <-- using this in html mode, app works i.e. no 406 error

    respond_to do |format|
      format.html { redirect_to(user_root_path) }  # <-- using this in html mode instead of above line, app fails i.e. 406 error
      # format.js  # <-- using this in ajax mode, app fails i.e. 406 error
    end
  end
end
4

2 回答 2

0

你想用“json”来响应,而不是用“js”(这里指的是 JavaScript)。jquery_ujs,为 增加功能的 gem method: :delete,需要 JSON。

def destroy
  @gcal_user = current_user.gcal_user
  @gcal_user.delete

  respond_to do |format|
    format.html { redirect_to user_root_path }
    format.json { head :no_content }
  end
end
于 2013-08-14T21:56:31.113 回答
0

问题是由路线引起的。使用单数resource :gcal_user而不是复数resources :gcal_users会导致 URL 的格式不同。单一资源使用“/gcal_user.[id]”,这导致respond_to块认为格式必须是“.[id]”而不是“.js”或“.html”。

请参阅Respond_to 不重定向,给出 406 Not Acceptable 错误

于 2013-08-24T16:32:32.350 回答