Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
205 views
in Technique[技术] by (71.8m points)

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

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.

I am using a form_for helper like so:

= 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!

Inspecting the request with firebug and sure enough the Content-Type http header on the ajax request is being set to 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.

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

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

Thanks for any help

question from:https://stackoverflow.com/questions/9583380/rails-3-remote-form-how-do-i-specify-the-content-type

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can set the content-type with:

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

As described in rails.js line 106.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...