简体   繁体   中英

How to pass data from controller to view with ajax in rails

I posted today similar questions two times

how-to-use-local-or-instance-variable-in-ruby-code-in-coffeescript-in-haml-templ

ajax-in-rails-returns-alway-error-callback

I'm confusing about these issues please let me ask.

I'm using ajax in haml to reload a part of page with data from controller.

Please see my code.

.html.haml

= render 'layouts/partial' #This is partial. I want to reload this part

:coffee
    $('input#field').change ->
        $.ajax
            url: '/posts/gaga'
            type: "POST"
            dataType: 'text'
            error: (jqXHR, textStatus, errorThrown) ->
                alert "error"
            success: (data, textStatus, jqXHR) ->
                alert "success"
                $('div.kore').html('#{ j( render( 'layouts/partial' ) )} ');

posts_controller.rb

def gaga
    @model = Model.new("blabla")
    render :text => @model
end

_partial.html.haml

- if @model
    = @model.html_safe
- else
    = "No data"

First, I thought data can be get through @model instance variable from controller but it couldn't.

Second, I tryed to get data from ajax response data to view(_partial.html.haml) with jQuery.

Callback and response return correctly as text.

How do I pass data to view from ajax response data, or is there other ways?

Sorry for my sloppy English. I hope someone give me the clue.

Thanks in advance!

You can set the ajax request to /posts/gaga.json and in your controller's gaga method:

respond_to do |format|
  format.html
  format.json { render :json => @model }
end

You may want to prepare gaga.html.haml view file if you intend to also access /posts/gaga not via ajax, or just remove format.html if you only intend to respond in json.


To clarify, I see you want to reload the partial after ajax request. So rather than:

$('div.kore').html('#{ j( render( 'layouts/partial' ) )} ');

you can do something like this:

# inside gaga methods
format.json do
  render(json: {
    view: render_to_string(partial: 'layouts/partial', layout: false)
  })
end

Now inside your view:

= render 'layouts/partial' #This is partial. I want to reload this part

:coffee
  $('input#field').change ->
    $.ajax
      url: '/posts/gaga.json'
      type: "POST"
      error: (jqXHR, textStatus, errorThrown) ->
        alert "error"
      success: (data, textStatus, jqXHR) ->
        alert "success"
        $('div.kore').html(data.view)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM