Rails,jQuery,.js.erb文件,JS不是由浏览器执行的 [英] Rails, jQuery, .js.erb files, JS not executed by the browser

查看:134
本文介绍了Rails,jQuery,.js.erb文件,JS不是由浏览器执行的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用jQuery,一切都很棒,直到现在,当我尝试渲染部分并将其附加到div时。以下是我设置的方法:

I'm trying to use jQuery, and everything has been great, until now, when I'm trying to render a partial and append it to a div. Here is how I have it set up:

我有一个响应js的动作:

I have an action that responds to js:

def index
  @objects = Object.find(:all)

  respond_to do |format|
    format.js
  end
end

还有一个名为的模板index.js.erb中包含一些javascript:

And a template called index.js.erb with some javascript in it:

alert("hello world");

Firebug返回text / javascript响应,其中包含:

Firebug returns a "text/javascript" response containing:

alert("hello world");

但是没有出现警报窗口,也没有其他任何JavaScript工作。我查看了 http://railscasts.com/episodes/136-jquery
和或多或少跟随。我尝试了其他一些东西,例如使用.rjs代替.erb并将其放在我的模板中:

But the alert window does not appear, nor does any other JavaScript work. I checked out http://railscasts.com/episodes/136-jquery And am more or less following along. I tried several other things, like using .rjs instead of .erb and putting this in my template:

page.alert("hello world"); 

但我得到了相同的结果,浏览器从不执行JS。

but I get the same exact result, and the browser never executes the JS.

任何人都知道为什么JavaScript没有被执行?

Anyone know why the JavaScript isn't being executed?

我正在运行Rails 2.3.4。

I'm running Rails 2.3.4.

推荐答案

您必须从您的视图中调用它,否则它将永远不会执行。

You have to call it from your view or it will never be executed.

示例控制器:

def index
  @objects = Object.find(:all)

  respond_to do |format|
    format.js{
      render :text => "alert('hello')"
    }
  end
end

和index.html.erb:

and an index.html.erb with:

<script type="text/javascript">
  $(function(){
    $.ajax({ url: '/controller', type: 'get', dataType:'script' });
  });
</script>

将'/ controller'替换为执行该控制器的索引操作的实际url,默认情况下为PostsController它将是'/ posts'等等...

replace '/controller' with the actual url that executes that controller's index action, by default for PostsController it will be '/posts' and so on...

如果你喜欢rjs你删除{}并在控制器中输入并创建一个index.js。 erb或index.rjs with:

if you like rjs you delete the {} and everithing in it in the controller and create an index.js.erb or index.rjs with:

page.alert("hello world")

或:

page << "hello world"

这篇关于Rails,jQuery,.js.erb文件,JS不是由浏览器执行的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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