rails render view onclick with javascript

前端 未结 3 1523
佛祖请我去吃肉
佛祖请我去吃肉 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 21:05

    One way you can try is to let the button click go to a controller action, by AJAX, and then render the file with name .js.erb. this file will then be able to call the render action.

    I will expatiate more with the following:

    Assuming the resource in question is Greetings and you have a dynamic_show action in the Greetings controller, for example, and you have a dynamic_show_greetings_path routing to this action.

    From inside your view, you can have:

    
    

    and the Greetings#dynamic_show action will be like follow:

    def dynamic_show
      respond_to do |format|
        format.js
      end
    end
    

    then, in your view directory, you have a dynamic_show.js.erb file, which will contain the script to append the dynamic view as follow:

    $('#show').html("<%=escape_javascript render(:partial => 'show') %>");
    

    And that solves it for you!

    Of course, to now make it dynamic, you have to then pass in params to the controller, and then render content based on the response gotten.

    PS:

    • setting remote: true on the link ensures that the call will be an AJAX call.
    • controller actions by default renders the file with same name as the action name, therefore, dynamic_show responding to js will render dynamic_show.js.erb

    Hope this throws a great light into it for you... ;)

提交回复
热议问题