从控制器调用javascript函数

编程入门 行业动态 更新时间:2024-10-09 06:27:06
本文介绍了从控制器调用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函数

本文发布于:2023-11-17 11:01:47,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1609802.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:控制器   函数   javascript

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!