Rails 3远程表单:如何指定内容类型?

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
表单按预期以ajax方式提交。但控制器返回的是HTML格式,而不是JSON格式!
通过Firebug检查请求,确认ajax请求上的Content-Type HTTP头被设置为application/html。
关于此问题的文档相当匮乏,使用:format => :json似乎仅仅将“.json”附加到表单操作中,并未实际修改任何HTTP头。
我也尝试了:content_type => :json,但没有效果。
我不能简单地硬编码控制器以返回JSON格式,因为在其他地方我确实需要它返回HTML格式...
那么,有谁知道如何告诉控制器在使用form_for时呈现JSON格式?
感谢任何帮助

你的表单标签在页面上呈现什么URL和方法? - iltempo
提交,完整的标签为:<form method="post" id="new_object" data-remote="true" class="new_object" action="/objects" accept-charset="UTF-8"> - Chris
没有json。你考虑使用request.xhr来区分ajax和普通请求,而不是请求的格式了吗? - iltempo
好的,我进行了快速测试,目前看来这似乎是一个解决方法。不确定它是否正确 - 格式和请求机制应该分开才对。如果我以后想添加另一个需要XML的ajax请求怎么办? - Chris
2个回答

53
你可以使用以下代码设置内容类型:
= form_for(@object, :remote => true, :html => {:'data-type' => 'json'})

rails.js第106行所述。

谢谢!我知道我漏掉了一些显而易见的东西! :) - Chris
18
在Rails 4中,您可以使用format::json(或:format =>:json)代替:html => {:'data-type' => 'json'} - James McMahon
@JamesMcMahon 在Rails 3.2中也是如此。 - RocketR
1
我的情况下不起作用 :( Rails 4中的form_for remote true不起作用,我在浏览器控制台中得到了这个错误Resource interpreted as Script but transferred with MIME type text/html 实际上响应以HTML表单的形式发送而不是JS。 - Taimoor Changaiz
2
这会在 ajax 请求中设置 dataType 属性,而不是 contentType。这将导致请求的 Accepts 标头更改为 json。但是,Content-Type 将保持不变。 - plainjimbo

7

对于Rails 5而言,正确的方法是设置一个数据属性 data: { type: :json }

JQuery UJS文档


3
有点沉重,@DavyM。他只是想帮忙,并通过链接UJS文档实际上帮了我个忙。 - EasyCo

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接