简体   繁体   English

避免在 ruby​​ on rails 项目中重新加载布局

[英]avoiding layout reloading in ruby on rails project

In ruby on rails , I want to load page data dynamically.在 ruby​​ on rails 中,我想动态加载页面数据。 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. Turbolinks - 这将比您想要的更令人耳目一新,但如果您经常做这种事情,您可能需要阅读一下。 https://github.com/rails/turbolinks https://github.com/rails/turbolinks

  2. Manually using ajax requests using the following approach:使用以下方法手动使用ajax请求:

A. Add the following gem to your Gemfile https://github.com/rails/jquery-ujs A. 将以下 gem 添加到您的 Gemfile https://github.com/rails/jquery-ujs

B. Include this in your JS. B. 将其包含在您的 JS 中。 eg In your JavaScript file, load it by including the following:例如,在您的 JavaScript 文件中,通过包含以下内容来加载它:

//= require jquery
//= require jquery_ujs 

C: Update your link to include remote: true: C: 更新您的链接以包含 remote: true:

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

D: Add a respond to js in your controller. D:在你的控制器中添加对 js 的响应。 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. E:在您的视图中创建一个名为 action_name.js.erb 的新文件。 You can then place any javascript code within this file.然后,您可以在此文件中放置任何 javascript 代码。 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.差不多就是这样,当您现在单击链接时,您的应用程序应该发送一个 ajax 请求,您应该在响应中获得呈现的 javascript,这反过来应该更新您希望替换的页面上的元素。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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