Calling javascript functions from controller

后端 未结 2 506
情话喂你
情话喂你 2020-12-23 23:42

Is it possible to call a javascript function from a controller in rails?

相关标签:
2条回答
  • 2020-12-24 00:18

    No, but you could output javascript that would be called immediately in your view e.g.

    <script type="text/javascript">
       function IWillBeCalledImmediately()
       {
          alert('called');
       };
       IWillBeCalledImmediately();
    </script>
    

    However it would probably be better to use jquery and use the ready event.

    <script type="text/javascript">
         $(function() { 
              alert('called');
          });
    </script>
    
    0 讨论(0)
  • 2020-12-24 00:45

    What I do is to make a Rails controller produce a javascript action. Is have it call a partial that has javascript included in it.

    Unless you want that activated on page load, I would set it up via AJAX. So that I make an AJAX call to the controller which then calls a javascript file.

    This can be seen via voting :

    First the AJAX

    //This instantiates a function you may use several times.
    
    jQuery.fn.submitWithAjax = function() {
      this.live("click", function() {
        $.ajax({type: "GET", url: $(this).attr("href"), dataType: "script"});
        return false;
      });
    };
    
    // Here's an example of the class that will be 'clicked'
    $(".vote").submitWithAjax();
    

    Second the Controller

    The class $(".vote") that was clicked had an attribute href that called to my controller.

    def vote_up
      respond_to do |format|
        # The action 'vote' is called here.
        format.js { render :action => "vote", :layout => false }
      end
    end
    

    Now the controller loads an AJAX file

    // this file is called vote.js.haml
    ==  $("#post_#{@post.id}").replaceWith("#{ escape_javascript(render :partial => 'main/post_view', :locals => {:post_view => @post}) }");
    

    You have successfully called a javascript function from a controller.

    0 讨论(0)
提交回复
热议问题