简体   繁体   中英

avoiding layout reloading in ruby on rails project

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.

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. eg 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. eg:

  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.

eg

$("#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.

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