rails render view onclick with javascript

前端 未结 3 1525
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-26 20:25

I\'m trying to create a view, where users can click on different buttons and render different content based on the buttons they click. I\'ve tried getting this done with JS but

3条回答
  •  广开言路
    2021-01-26 20:49

    There are two ways to do this.

    Firstly, if you're wanting to load the JS on-page, you need to use what @anchalee suggested, and preload the content with some sort of "hide" class in the CSS:

    #app/assets/javascripts/application.js
    $(document).on("click", "a.hidden", function(e){
       e.preventDefault();
       el = $(this).attr("href");
       $(el).toggle();
    });
    
    #app/views/controller/your_view.html.erb
    <%= link_to "User", "#user", class: "hidden" %>
    
    

    This will take any divs with the id specified by the href attribute of the link, and then make it so that the div will hide or show depending on its current state.

    --

    Secondly, you have the off-page method (using ajax).

    This is used to get data from the server, and will be where you'd load server-centric data such as what you're trying to do now.

    Doing this is actually quite simple:

    #app/controllers/your_controller.rb
    class YourController < ApplicationController
       layout: Proc.new{|c| !c.request.xhr? }
    end
    

    This will return any data you need without the layout:

    #app/assets/javascripts/application.js
    $(document).on("click", "#show", function(e){
       e.preventDefault();
       $.get($(this).attr("href"), function(data){
          $("#show").html(data);
       });
    });
    
    #app/views/your_controller/show.html.erb
    <%= link_to "Show", [[url for page]], id: "show" %>
    

提交回复
热议问题