1

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

应用程序/控制器/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

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

4

1 回答 1

3

啊,它说“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)

于 2013-01-05T02:23:46.177 回答