我使用的是Rails 3.2,我有一个表单,我希望它通过ajax发布,并让控制器返回json.

我使用表格_作为助手,如下所示:

= form_for(@object, :remote => true, :format => :json) do |f|
....

我的对象控制器创建方法如下所示:

  def create
    respond_to do |format|
      if @object.save
         format.html { redirect_to @object }
         format.json { render json: @object, status: :created, location: @object }
      else
        format.html { render action: "new" }
        format.json { render json: @object.errors, status: :unprocessable_entity }
      end
    end
  end

表单正在按预期提交ajaxly.但是控制器返回的是html,而不是json!

使用firebug判断请求,确保ajax请求上的内容类型http头被设置为application/html.

The documentation around this is pretty sparse, :format => :json seems to just append ".json" to the forms action, not actually modify any http headers.

I've also tried :content_type => :json to no effect.

我不能简单地硬编码控制器以返回json,因为我确实希望它在其他地方返回html...

那么,有人知道如何告诉控制器在使用form_for时呈现json吗?

谢谢你的帮助

推荐答案

您可以使用以下选项设置内容类型:

= form_for(@object, :remote => true, :html => {:'data-type' => 'json'})

rails.js第106行所述.

Ruby-on-rails相关问答推荐

rails中Net::STP的多文件模式

Rails 7.1.3如何在生产环境中查看堆栈跟踪

如何将POST-CSSS-IMPORT与TRANWIND-RACKS和IMPORT映射一起使用

多对多模型通过控制台创建记录不起作用

无法在 Rails 中使用 wkhtmltopdf 写入临时文件

使用嵌套属性时如何自动将父 ID 分配为外键?

Rails 创建自定义函数/方法以及存储位置

我如何在不在 gemfile 中的 rake 任务中要求 gem?

正确更新其他列的更新列

URL 中的 Rails slugs - 使用 Active Record Model Post 的 Title 属性而不是 ID

Heroku 应用程序上的远程 mysql 数据库

如何避免 RSpec 3.0 中 stub_chain 的弃用警告?

在 Ruby on Rails 上,我们如何在控制器中打印调试信息?

DateTime.now 还是 Time.now?

如何在 Rails 应用程序中使用长 id?

如何将变量传递给render_to_string?

强参数需要多个

Ruby on Rails 3:通过 Rails 将数据流式传输到客户端

我的 JavaScript 模式/实践很糟糕.我应该go 哪里寻求帮助?

在 Rails 3 中设置会话超时