是否可以从rails中的控制器调用javascript函数?
Is it possible to call a javascript function from a controller in rails?
推荐答案我所做的是让Rails控制器产生一个javascript动作。让它调用包含javascript的部分。
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.
除非你想在页面加载时激活它,否则我会通过AJAX进行设置。因此,我向控制器发出一个AJAX调用,然后调用一个javascript文件。
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.
这可以通过投票看到:
首先是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();控制器第二
点击的类 $(。vote)有一个调用我的控制器的属性href。
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现在控制器加载一个AJAX文件
// this file is called vote.js.haml == $("#post_#{@post.id}").replaceWith("#{ escape_javascript(render :partial => 'main/post_view', :locals => {:post_view => @post}) }");您已成功从控制器调用了javascript函数。
You have successfully called a javascript function from a controller.
更多推荐
从控制器调用javascript函数
发布评论