从jQuery调用Rails函数? [英] call a rails function from jquery?

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

问题描述

是否有可能在jQuery中调用rails函数或访问rails对象? 我想做类似的事情:

is it somehow possible to call a rails function or to access a rails object from within jQuery? I'd like to do something like:

jQuery(document).ready(function($) {
$('#mydiv').html("<%= @object.name %>");
});

OR

jQuery(document).ready(function($) {
$('#mydiv').html("<%= render :partial => "contacts" %>");
});

此刻,我将所有jQuery内容都保留在布局中包含的application.js中.哦,是的....而且我没有使用Rails Edge.

At the moment I'm keeping all my jQuery stuff in my application.js, which is included in my layout. Oh yeah....and I'm not using Rails Edge.

此致

塞巴斯蒂安

推荐答案

您必须在控制器中有一个方法,该方法可以呈现所需的内容.另一种方法是使用视图块,例如在布局视图的末尾

You'll have to have a method in the controller that will render what you need, if you want to do that. Another way to do it is to use view blocks, like in the end of your layout view

<script type="text/javascript">
<%= yield :footerjs %>
</script>

,然后在视图中执行以下操作:

and in the view do something like:

<% content_for :footerjs do %>
jQuery(document).ready(function($) {
$('#mydiv').html('<%= escape_javascript(render :partial => "contacts") %>');
});
<% end %>

您需要确保要渲染的部分不会包含可能导致javascript错误的字符(例如在字符串末尾加引号等).另外,某些浏览器不喜欢多行字符串,因此您也必须弄弄它.

You'll need to make sure that the partial you'll be rendering won't have characters that may cause javascript errors (like finishing the quotes before the end of the string, etc). Also, some browsers don't like multi-line strings, so you'll have to fiddle with that as well.

这篇关于从jQuery调用Rails函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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