简体   繁体   中英

Execute Javascript function from Rails controller (without rendering or reloading the view)

Is it possible to execute a Javascript function included in application.js or the corresponding js.coffee file from a controller, but without rendering or reloading the view? Ie just a simple

def connect()
  call js: "connect_through_javascript();"
  render :nothing => true
end

but instead of rendering :nothing, is there some way the view could be left untouched? Also would it be possible to send params with it, ie

def connect(param1, param2, param3)
  call js: "connect_through_javascript(#{param1}, #{param2}, #{param3});"
  render :nothing => true
end

The Javascript function called will in turn go to another controller action for it's callback.

I'm about to try with the Paloma gem, but I just wanted to know if any of this is possible without adding dependencies.

What you want is AJAX. JavaScript will then have to do something intelligent with the HTTP response body in the success callback if using a JavaScript library, like jQuery, or if the readyState is 4 and the status is 200 if using native JavaScript.

You're stuck with the HTTP request-response lifecycle.

EDIT: Here is a simple example:

The HTML

<ol id="comments"></ol>

<script type="text/javascript">
    var xhr = new XMLHttpRequest();

    xhr.onreadystatechange = function() {
        if (this.readyState === 4 && this.status === 200) {
            document.getElementById("comments").innerHTML = this.responseText;
        }
    };

    xhr.open("GET", "/posts/123/comments_ajax");

    xhr.send(null);
</script>

The Rails Controller

class PostsController < ApplicationController

    def comments_ajax
        @comments = Comment.where(:post_id => params[:id])
    end

end

The contents of app/views/posts/comments_ajax.html.erb :

<%= @comments.each |comment| do %>
    <li><%= comment.text %></li>
<% end %>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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