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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9583380/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 02:58:49  来源:igfitidea点击:

Rails 3 remote form: How do I specify the content type?

ruby-on-railsajaxruby-on-rails-3formsujs

提问by Chris

I am using Rails 3.2, I have a form and I want it to be posted via ajax and have the controller return json.

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

I am using a form_for helper like so:

我正在使用 form_for 助手,如下所示:

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

My objects controller create method looks like this:

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

  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

The form is submitting ajaxly as expected. But the controller is returning html, not json!

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

Inspecting the request with firebug and sure enough the Content-Type http header on the ajax request is being set to application/html.

使用 firebug 检查请求,果然 ajax 请求上的 Content-Type 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.

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

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

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

I can't simply hard code the controller to return json as there are other places where I do want it to return html...

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

So does anyone know how to tell the controller to render json when using form_for?

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

Thanks for any help

谢谢你的帮助

回答by spas

You can set the content-type with:

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

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

As described in rails.jsline 106.

rails.js第 106 行所述。

回答by Brian C

For Rails 5, the proper way is to set a data attribute data: { type: :json }.

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

JQuery UJS docs

JQuery UJS 文档