【问题标题】:Why is a controller respond_to that is set to js returning only html in Ruby on Rails?为什么设置为 js 的控制器 respond_to 在 Ruby on Rails 中只返回 html?
【发布时间】:2013-01-05 02:16:21
【问题描述】:

即使我明确声明它只能以 JS 类型返回,为什么我的控制器操作也只能以 HTML 格式返回?

app/controllers/classrooms_controller.rb

def create
  respond_to do |format|
    format.js # This doesn't work.
  end
end

app/views/classrooms/new.html.haml

= form_tag classrooms_path, :html => {:multipart => true}, do |f|
  = text_field_tag :name
  = submit_tag "Done"

app/views/classrooms/create.js.erb

alert('hi');

服务器

Started POST "/classrooms" for 127.0.0.1 at 2013-01-04 18:17:22 -0800
Processing by ClassroomsController#create as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"Z+rsjO1rY2+P7VdsYd/LwiQr3DZX6r1/Dxh7JGbIOFA=", "name"=>"feed", "commit"=>"Done"}
Completed 406 Not Acceptable in 2ms

我在浏览器中得到一个没有代码的空白页面(检查了源代码)。

【问题讨论】:

  • 能否包含请求的完整日志?
  • 好的,更新了。感谢收看!

标签: ruby-on-rails ruby-on-rails-3


【解决方案1】:

啊,它说“406 Not Acceptable”,您正在从表单发出 HTML 请求,但您的控制器只响应 JS 请求。

尝试在表单中添加 :remote => true

= form_tag classrooms_path, :html => {:multipart => true}, :remote => true, do |f|

如果这不起作用,您可能没有包括这些:

= javascript_include_tag :defaults
= csrf_meta_tag

在您的 html 标头中 (http://stackoverflow.com/questions/4227775/rails-form-for-remote-true-is-not-calling-js-method)

【讨论】:

  • 406 Not Acceptable 代表什么?它非常模糊,对诊断问题没有帮助..
  • 这是 html 错误代码,这将对您有所帮助,checkupdown.com/status/E406.html。基本上只使用 format.js,你是说你只接受 JS 请求,但是从表单创建的请求默认是 HTML(除非你使用 :remote => true)。
  • 你摇滚。感谢您的帮助!
猜你喜欢
  • 1970-01-01
  • 2020-10-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多