【问题标题】:406 Not Acceptable error on jQuery :remote => true linkjQuery 上的 406 Not Acceptable 错误:remote => true 链接
【发布时间】:2011-02-07 03:32:38
【问题描述】:

我正在通过锚标记链接提交删除请求,并使用 :remote => true 通过 JS 提交以使用 jQuery。我在其他两个与此相同的情况下完成了此操作,完全没有问题。但由于某种原因,这会导致问题 - 每当我提交时,我都会收到 406 Not Acceptable 错误。

销毁链接

content_tag( :p, link_to("+#{vote.weight}", unvote_path(vote), :method => :delete, :remote => true ), :class => "chosen" )

routes.rb

delete "/unvote" => "votes#destroy", :as => :unvote

votes_controller.rb

def destroy
    @vote = Vote.find(params[:format])
    if !current_user.owns(@vote)
      flash[:alert] = "You cannot remove votes that aren't yours!"
    end
    @idea = @vote.idea
    @vote.destroy

    respond_with @vote do |format|
      format.js
      format.html { redirect_to category_idea_path(@idea.category, @idea) }
    end
end

destroy.js.erb

$('#vote_buttons').append('<%= escape_javascript get_vote_buttons(@idea.category, current_user, @idea) %>');

这与我在 new.js.erb 中的行完全相同,而且效果很好(除了它没有返回我想要的内容,但它至少可以执行并正确附加)。

application.js

jQuery.ajaxSetup({
    'beforeSend': function(xhr) { 
        xhr.setRequestHeader("Accept", "text/javascript");
    },
    cache: false
 });

如果我理解正确的话,我在 application.js 中找到了它应该正确设置标题。

另外,请注意该链接正确执行其删除功能 - 当我手动刷新页面时,投票已被删除。唯一的问题似乎是 destroy.js.erb

返回的内容

知道为什么这与我的其他工作示例不同吗?我整天都在努力解决这个问题,无法弄清楚。

【问题讨论】:

  • 您是否使用 firebug 检查过您发送和接收的请求类型?还要检查你的日志,你得到的请求应该是 * / *
  • 响应头:内容类型文本/html;字符集=utf-8。请求标头:接受 /;q=0.5, text/javascript, application/javascript。我已经有点认为这是问题所在,但我无法让它返回正确的请求(文本/javascript),即使它所做的一切都与我的其他删除链接相同。
  • 好的,结果我在这里的实现与我的其他删除链接并不完全相同。问题似乎与:unvote 路径有关 - 当我删除它并使用category_idea_vote_path(etc) 时,它起作用了。我不知道是否有办法让它与自定义路线一起工作,但这似乎是我试图太聪明的一个例子,它又回来咬我:(

标签: jquery ruby-on-rails-3 http-status-codes http-status-code-406


【解决方案1】:

您不必在销毁链接中添加 :method => :delete 吗?此外,您可能不想使用 new_category_idea_vote_path 来生成销毁链接,而只是使用 category_idea_vote_path

这样:

content_tag( :p, link_to("+#{i}", category_idea_vote_path(category, idea, :weight => i), :remote => true, :method => :delete ), :class => "valid" )

看这个例子:

  link_to("Destroy", "http://www.example.com", :method => :delete, :confirm => "Are you sure?")

http://api.rubyonrails.org/classes/ActionView/Helpers/UrlHelper.html#method-i-link_to

【讨论】:

  • 呸,对不起斯特凡。我复制了错误的一段代码——我最初拥有的是新的投票链接,它工作正常。我已经使用正确的销毁链接更新了问题,以及 routes.rb 中的相关行以定义 unvote_path。如果你能再找我看看,那将不胜感激!另请注意,该链接完美地执行其删除功能 - 当我手动刷新页面时,投票已被正确删除。
猜你喜欢
  • 2014-11-12
  • 2016-02-21
  • 2012-07-23
  • 2012-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-06-24
  • 2015-03-13
相关资源
最近更新 更多