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

Categories

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

javascript - 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.

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...