从控制器调用javascript函数

ssr*_*sri 5 javascript ruby-on-rails

是否可以从rails中的控制器调用javascript函数?

Tri*_*rip 13

我所做的是让Rails控制器产生一个javascript动作.有它调用包含javascript的部分.

除非你想在页面加载时激活,否则我会通过AJAX进行设置.这样我就向控制器发出一个AJAX调用,然后调用一个javascript文件.

这可以通过投票看到:

首先是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();
Run Code Online (Sandbox Code Playgroud)

第二个控制器

$(".vote")单击的类具有调用我的控制器的属性href.

def vote_up
  respond_to do |format|
    # The action 'vote' is called here.
    format.js { render :action => "vote", :layout => false }
  end
end
Run Code Online (Sandbox Code Playgroud)

现在控制器加载一个AJAX文件

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

您已成功从控制器调用了javascript函数.