37

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

我正在使用这样的 form_for 助手:

= 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

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

使用 firebug 检查请求,并确定将 ajax 请求上的 Content-Type http 标头设置为 application/html。

围绕此的文档非常稀疏, :format => :json 似乎只是将“.json”附加到表单操作中,实际上并未修改任何 http 标头。

我也试过 :content_type => :json 没有效果。

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

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

谢谢你的帮助

4

2 回答 2

53

您可以使用以下方式设置内容类型:

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

rails.js第 106 行所述。

于 2012-03-06T12:45:50.143 回答
7

对于 Rails 5,正确的方法是设置 data 属性 data: { type: :json }

jQuery UJS 文档

于 2017-08-01T00:29:52.850 回答