Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

In ruby on rails , I want to load page data dynamically. But that time i don't want to refresh or load layout page, only body should render.I am having two pages and when i switch from one page to another then the layout page data should not be reload, only another page data should load.

See Question&Answers more detail:os

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

1 Answer

There are two different approaches you could take here.

  1. Turbolinks - This will refresh a little more than what it sounds like you want, but if you are doing this kind of thing a lot, you may want to take a read. https://github.com/rails/turbolinks

  2. Manually using ajax requests using the following approach:

A. Add the following gem to your Gemfile https://github.com/rails/jquery-ujs

B. Include this in your JS. e.g. In your JavaScript file, load it by including the following:

//= require jquery
//= require jquery_ujs 

C: Update your link to include remote: true:

<%= link_to 'New page', page_path, remote: true %>

D: Add a respond to js in your controller. e.g.:

  def action_name
    respond_to do |format|
      format.html
      format.js
    end
  end

E: Create a new file named action_name.js.erb in your views. You can then place any javascript code within this file. So you can target a specific element on the page and replace it with a partial.

e.g.

$("#id_of_element_on_page").html("<%= escape_javascript(render(partial: 'page_content', locals: { project: @project })) %>");

That's pretty much it, when you now click on the link, you app should send an ajax request and you should get the rendered javascript in the response which in turn should update the element on the page you wish to replace.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...