从控制器调用javascript函数 [英] Calling javascript functions from controller

查看:135
本文介绍了从控制器调用javascript函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以从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函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆